Tuesday, April 2, 2013

Reset .net validation controls client side

On many occasions we provide form reset functionality and people handle it client side or server side. In general we validate input from the user and show proper validation message. But sometimes it happens that user has entered wrong input and thus it will display validation messages. Now if you have handled form reset functionality client side, you must reset all validation message as well. You can do it as shown in below code:

  function ResetForm() {
            $('input[type=text], textarea').val('');
            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;

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

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

Page_Validators : This is an array containing all of 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 validation control’s display property is set to dynamic, if yes then it will set css style of that validator to none.

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

I hope it helps!


Anonymous said...

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.

Anonymous said...

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

Nilesh Thakker said...

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!