Reset .net validation controls client side

We often provide form reset functionality, and people handle it client-side or server-side. Generally, we validate user input and show the proper validation messages. But sometimes, the user has entered the wrong information, and thus it will display validation messages. Now, if you have handled form reset functionality client-side, you must also reset all validation messages. You can do it as shown in the below code:

Javascript:

 function ResetForm() {
            $('input[type=text], textarea').val('');
            Page_ClientValidateReset();
            return false;
        }

        function Page_ClientValidateReset() {
            if (typeof (Page_Validators) != "undefined") {
                for (var i = 0; i < Page_Validators.length; i++) {
                    var validator = Page_Validators[i];
                    validator.isvalid = true;
                    ValidatorUpdateDisplay(validator);
                }
            }
        }

HTML:

<asp:Button ID="btnReset" runat="server" Text="Reset" OnClientClick="return ResetForm();" />

Now let’s understand what JavaScript properties and functions are.

Page_Validators: This array contains all the validators on the page.

isvalid: This is a property on each client validator indicating whether it is currently valid.

ValidatorUpdateDisplay: Inbuilt function which checks whether the validation control’s display property is dynamic; if yes, then it will set the CSS style of that validator to none.

So basically, it loops through all the validators, sets isvalid property to true and set validators’ visibility to none. Here we’re not using the form reset function to clear form fields as Reset doesn’t clear a form; it simply sets the form value to its default which may or may not be blank.

I hope it helps!


Posted

in

,

by

Comments

3 responses to “Reset .net validation controls client side”

  1. Anonymous Avatar
    Anonymous

    That works fantastic! I was pulling my hair (StackOverFlow was no help either) for 7 hours on this man! I just wanted a RESET button to reset the controls without it having to call code behind and trigger my validation controls, therefore preventing the reset method to even kick in!Well done.

  2. Anonymous Avatar
    Anonymous

    But how can I do the same to reset checkboxes and other controls?

  3. Nilesh Thakkar Avatar

    You could use something like below to clear/reset checkbox/radio buttons (consider you're resetting form's controls): $('#YourformId').find('input:radio, input:checkbox') .removeAttr('checked').removeAttr('selected');I hope it helps!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: