187

I am using the jQuery validation plugin for client side validation. Function editUser() is called on click of 'Edit User' button, which displays error messages.

But I want to clear error messages on my form, when I click on 'Clear' button, that calls a separate function clearUser().

function clearUser() {
    // Need to clear previous errors here
}

function editUser(){
    var validator = $("#editUserForm").validate({
        rules: {
            userName: "required"
        },
        errorElement: "span",
        messages: {
            userName: errorMessages.E2
        }
    });

    if(validator.form()){
        // Form submission code
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vicky
  • 9,515
  • 16
  • 71
  • 88

30 Answers30

230

You want the resetForm() method:

var validator = $("#myform").validate(
   ...
   ...
);

$(".cancel").click(function() {
    validator.resetForm();
});

I grabbed it from the source of one of their demos.

Note: This code won't work for Bootstrap 3.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Parrots
  • 26,658
  • 14
  • 59
  • 78
  • 34
    For those using bootstrap, there are cases where `resetForm()` does not clear all the instances of `.error` on the child elements of the form. This will leave residual CSS like red text color unless you call `.removeClass()`. Example: `$('#myform .control-group').removeClass('error');` – jlewkovich May 30 '14 at 15:13
  • 14
    Using bootstrap 3 this doesn't hide the field validation errors. What a shame. – The Muffin Man Oct 16 '14 at 20:28
  • 2
    It works for me with Bootstrap 3. Perhaps the problem is with your integration of both libraries? – bernie Dec 07 '15 at 18:15
  • 4
    No this resetForm will literally even rest the form data, too. – Codemole Nov 16 '17 at 07:46
  • what @JLewkovich says using bootstrap3 is true, must implement a manual resetting jumping into the inspector and figuring out what classes are applying on errors – Nestor Colt Jan 18 '18 at 14:23
  • put this class on your (s)css: .field-validation-valid{ display: none; } and call the method .resetForm() – Kross Jun 07 '20 at 23:42
140

I came across this issue myself. I had the need to conditionally validate parts of a form while the form was being constructed based on steps (i.e. certain inputs were dynamically appended during runtime). As a result, sometimes a select dropdown would need validation, and sometimes it would not. However, by the end of the ordeal, it needed to be validated. As a result, I needed a robust method which was not a workaround. I consulted the source code for jquery.validate.

Here is what I came up with:

  • Clear errors by indicating validation success
  • Call handler for error display
  • Clear all storage of success or errors
  • Reset entire form validation

    Here is what it looks like in code:

    function clearValidation(formElement){
     //Internal $.validator is exposed through $(form).validate()
     var validator = $(formElement).validate();
     //Iterate through named elements inside of the form, and mark them as error free
     $('[name]',formElement).each(function(){
       validator.successList.push(this);//mark as error free
       validator.showErrors();//remove error messages if present
     });
     validator.resetForm();//remove error class on name elements and clear history
     validator.reset();//remove all error and success data
    }
    //used
    var myForm = document.getElementById("myFormId");
    clearValidation(myForm);
    

    minified as a jQuery extension:

    $.fn.clearValidation = function(){var v = $(this).validate();$('[name]',this).each(function(){v.successList.push(this);v.showErrors();});v.resetForm();v.reset();};
    //used:
    $("#formId").clearValidation();
    
  • Travis J
    • 81,153
    • 41
    • 202
    • 273
    • 2
      thats great , this solution is also working with "ValidationMessageFor" – Syed Ali Apr 04 '16 at 09:55
    • 1
      Great! Works perfectly with Bootstrap and MVC! – swissben Nov 25 '16 at 07:31
    • 5
      First of all, thanks! Had this working great for years, but now I've discovered a performance issue: `showErrors` does some DOM manipulation and it is called for every element in the form. The browser froze for a couple of seconds when using this code on a form with ~ 30 controls. The solution for me was to move `showErrors` out of the loop and just call it once right before `validator.resetForm`. As far as I can tell, it behaves exactly the same way and is a lot faster. – Michael Sandino Jun 08 '18 at 10:01
    • 1
      I've been using this until today that I found that if I use this method on the "Reset" button, it removes all the errors but there is no validation anymore... even if I try to validate again, everything is valid – Savandy Mar 27 '19 at 09:40
    61

    If you want to simply hide the errors:

    $("#clearButton").click(function() {
      $("label.error").hide();
      $(".error").removeClass("error");
    });
    

    If you specified the errorClass, call that class to hide instead error (the default) I used above.

    Nick Craver
    • 623,446
    • 136
    • 1,297
    • 1,155
    • 2
      @mark - correct, but it's not designed to...they are still invalid, we're just hiding the error messages in this case. This is alternative to the accepted answer for cases where you *specifically* want to hide (not ignore, e.g. disallow submission) the errors. It comes up more often that you'd think :) – Nick Craver Sep 02 '12 at 15:44
    • 2
      The problem is when you reset the form back and edit it again. My error dialog displays the count of errors and the count just keeps to sum up. Even 'resetForm' does not help. – mark Sep 02 '12 at 18:19
    • 2
      Even I did this, but it leads to another issue. The validations don't apply the next time the dialog opens up! – Vandesh May 26 '14 at 04:57
    • This technique worked for me on a Bootstrap 3 website. Just had to alter the error class to the following: `$(".has-error").removeClass("has-error");` – Myke Black Jul 17 '15 at 12:09
    51

    If you didn't previously save the validators apart when attaching them to the form you can also just simply invoke

    $("form").validate().resetForm();
    

    as .validate() will return the same validators you attached previously (if you did so).

    Juri
    • 32,424
    • 20
    • 102
    • 136
    32

    If you want to do it without using a separate variable then

    $("#myForm").data('validator').resetForm();
    
    Peter Mortensen
    • 30,738
    • 21
    • 105
    • 131
    Abhijit Mazumder
    • 8,641
    • 7
    • 36
    • 44
    20

    Unfortunately, validator.resetForm() does NOT work, in many cases.

    I have a case where, if someone hits the "Submit" on a form with blank values, it should ignore the "Submit." No errors. That's easy enough. If someone puts in a partial set of values, and hits "Submit," it should flag some of the fields with errors. If, however, they wipe out those values and hit "Submit" again, it should clear the errors. In this case, for some reason, there are no elements in the "currentElements" array within the validator, so executing .resetForm() does absolutely nothing.

    There are bugs posted on this.

    Until such time as they fix them, you need to use Nick Craver's answer, NOT Parrots' accepted answer.

    Meower68
    • 929
    • 9
    • 21
    8

    You can use:

    $("#myform").data('validator').resetForm();
    
    Brain Balaka
    • 123
    • 1
    • 4
    6

    I think we just need to enter the inputs to clean everything

    $("#your_div").click(function() {
      $(".error").html('');
      $(".error").removeClass("error");
    });
    
    Karra Max
    • 112
    • 2
    • 9
    5

    If you want just clear validation labels you can use code from jquery.validate.js resetForm()

    var validator = $('#Form').validate();
    
    validator.submitted = {};
    validator.prepareForm();
    validator.hideErrors();
    validator.elements().removeClass(validatorObject.settings.errorClass);
    
    sad comrade
    • 1,341
    • 19
    • 21
    3

    I tested with:

    $("div.error").remove();
    $(".error").removeClass("error");
    

    It will be ok, when you need to validate it again.

    Zaheer Ahmed
    • 28,160
    • 11
    • 74
    • 110
    Trung
    • 31
    • 1
    3

    For those using Bootstrap 3 code below will clean whole form: messages, icons and colors...

    $('.form-group').each(function () { $(this).removeClass('has-success'); });
    $('.form-group').each(function () { $(this).removeClass('has-error'); });
    $('.form-group').each(function () { $(this).removeClass('has-feedback'); });
    $('.help-block').each(function () { $(this).remove(); });
    $('.form-control-feedback').each(function () { $(this).remove(); });
    
    Emmanuel DURIN
    • 4,803
    • 2
    • 28
    • 53
    2

    If you want to hide a validation in client side that is not part of a form submit you can use the following code:

    $(this).closest("div").find(".field-validation-error").empty();
    $(this).removeClass("input-validation-error");
    
    mbadeveloper
    • 1,272
    • 9
    • 16
    2

    Tried every single answer. The only thing that worked for me was:

    $("#editUserForm").get(0).reset();
    

    Using:

    jquery-validate/1.16.0
    
    jquery-validation-unobtrusive/3.2.6/
    
    Artur Kedzior
    • 3,994
    • 1
    • 36
    • 58
    2

    None of the other solutions worked for me. resetForm() is clearly documented to reset the actual form, e.g. remove the data from the form, which is not what I want. It just happens to sometimes not do that, but just remove the errors. What finally worked for me is this:

    validator.hideThese(validator.errors());
    
    jlh
    • 4,349
    • 40
    • 45
    2

    Function using the approaches of Travis J, JLewkovich and Nick Craver...

    // NOTE: Clears residual validation errors from the library "jquery.validate.js". 
    // By Travis J and Questor
    // [Ref.: https://stackoverflow.com/a/16025232/3223785 ]
    function clearJqValidErrors(formElement) {
    
        // NOTE: Internal "$.validator" is exposed through "$(form).validate()". By Travis J
        var validator = $(formElement).validate();
    
        // NOTE: Iterate through named elements inside of the form, and mark them as 
        // error free. By Travis J
        $(":input", formElement).each(function () {
        // NOTE: Get all form elements (input, textarea and select) using JQuery. By Questor
        // [Refs.: https://stackoverflow.com/a/12862623/3223785 , 
        // https://api.jquery.com/input-selector/ ]
    
            validator.successList.push(this); // mark as error free
            validator.showErrors(); // remove error messages if present
        });
        validator.resetForm(); // remove error class on name elements and clear history
        validator.reset(); // remove all error and success data
    
        // NOTE: For those using bootstrap, there are cases where resetForm() does not 
        // clear all the instances of ".error" on the child elements of the form. This 
        // will leave residual CSS like red text color unless you call ".removeClass()". 
        // By JLewkovich and Nick Craver
        // [Ref.: https://stackoverflow.com/a/2086348/3223785 , 
        // https://stackoverflow.com/a/2086363/3223785 ]
        $(formElement).find("label.error").hide();
        $(formElement).find(".error").removeClass("error");
        $(formElement).find(".is-valid").removeClass("is-valid");
    
    }
    
    clearJqValidErrors($("#some_form_id"));
    
    Eduardo Lucio
    • 1,771
    • 2
    • 25
    • 43
    2

    I am using aspnet jquery-validation-unobtrusive and the following function cleared the validation errors for me:

    function clearFormValidations(formElement) {
        $(formElement).validate().resetForm();
    
        // reset unobtrusive validation summary, if it exists
        $(formElement).find("[data-valmsg-summary=true]")
            .removeClass("validation-summary-errors")
            .addClass("validation-summary-valid")
            .find("ul").empty();
    
        // reset unobtrusive field level, if it exists
        $(formElement).find("[data-valmsg-replace]")
            .removeClass("field-validation-error")
            .addClass("field-validation-valid")
            .empty();
    }
    

    usage:

    // to clear the errors:
    var myForm = document.getElementById('myFormId');
    clearFormValidations(myForm);
    
    // to validate again
    var validator = $(myForm).validate();
    validator.form();
    

    I found the above function here

    Hooman Bahreini
    • 14,480
    • 11
    • 70
    • 137
    • My code to remove the error message on the field StreetNumber: $("[data-valmsg-for='StreetNumber'] span").removeClass("field-validation-error").addClass("field-validation-valid").empty().css("padding", "0"); – Canada Wan Feb 15 '22 at 15:11
    1
    var validator = $("#myForm").validate();
    validator.destroy();
    

    This will destroy all the validation errors

    Miriam Farber
    • 18,986
    • 14
    • 61
    • 76
    kiran
    • 71
    • 5
    1

    In my case helped with approach:

    $(".field-validation-error span").hide();
    
    Taras Strizhyk
    • 135
    • 1
    • 2
    • 9
    0

    To remove the validation summary you could write this

    $('div#errorMessage').remove();

    However, once you removed , again if validation failed it won't show this validation summary because you removed it. Instead use hide and display using the below code

    $('div#errorMessage').css('display', 'none');
    
    $('div#errorMessage').css('display', 'block');  
    
    Grzegorz Piwowarek
    • 13,172
    • 8
    • 62
    • 93
    0

    None of the above solutions worked for me. I was disappointed at wasting my time on them. However there is an easy solution.

    The solution was achieved by comparing the HTML mark up for the valid state and HTML mark up for the error state.

    No errors would produce:

            <div class="validation-summary-valid" data-valmsg-summary="true"></div>
    

    when an error occurs this div is populated with the errors and the class is changed to validation-summary-errors:

            <div class="validation-summary-errors" data-valmsg-summary="true"> 
    

    The solution is very simple. Clear the HTML of the div which contains the errors and then change the class back to the valid state.

            $('.validation-summary-errors').html()            
            $('.validation-summary-errors').addClass('validation-summary-valid');
            $('.validation-summary-valid').removeClass('validation-summary-errors');
    

    Happy coding.

    0

    Try to use:

    onClick="$('.error').remove();"
    

    on Clear button.

    Alfred
    • 21,058
    • 61
    • 167
    • 249
    ZhukovRA
    • 506
    • 1
    • 3
    • 17
    0

    If you want to reset numberOfInvalids() as well then add following line in resetForm function in jquery.validate.js file line number: 415.

    this.invalid = {};
    
    Maximus
    • 2,906
    • 4
    • 35
    • 55
    0

    I just did

    $('.input-validation-error').removeClass('input-validation-error');

    to remove red border on the input error fields.

    0

    $(FORM_ID).validate().resetForm(); is still not working as expected.

    I am clearing form with resetForm(). It works in all case except one!!

    When I load any form via Ajax and apply form validation after loading my dynamic HTML, then after when I try to reset the form with resetForm() and it fails and also it flushed off all validation I am applying on form elements.

    So kindly do not use this for Ajax loaded forms OR manually initialized validation.

    P.S. You need to use Nick Craver's answer for such scenario as I explained.

    Peter Mortensen
    • 30,738
    • 21
    • 105
    • 131
    Parixit
    • 3,829
    • 3
    • 37
    • 61
    0

    validator.resetForm() method clear error text. But if you want to remove the RED border from fields you have to remove the class has-error

    $('#[FORM_ID] .form-group').removeClass('has-error');
    
    jay
    • 1,710
    • 2
    • 13
    • 16
    0

    Write own code because everyone uses a different class name. I am resetting jQuery validation by this code.

    $('.error').remove();
            $('.is-invalid').removeClass('is-invalid');
    
    Sumit Kumar Gupta
    • 2,132
    • 1
    • 22
    • 21
    0

    None of above worked for bootstrap 4. This solved problem for me:

    $('#formId .invalid-feedback').remove()
    $('#formId input').removeClass('is-valid');
    $('#formId input').removeClass('is-invalid');
    
    user1892777
    • 131
    • 2
    • 7
    0

    For v1.19.0 for JQuery Validation I found this one line of code worked for me:

    $('.field-validation-error').removeClass('field-validation-error').addClass('field-validation-valid').html('');
    

    In effect making the field appear valid to the user but when they click submit again the validation re-fires.

    Stephen Garside
    • 1,185
    • 10
    • 15
    0

    I took what other have posted and dug a little deeper and came up with this: In my form I added

    class="EditProv"
    

    to all my elements.

    var validator = $("#FormEditProvider").validate();
    validator.resetForm();
    validator.reset();
    $('#FormEditProvider .EditProv').removeClass('input-validation-error');
    $("[id^=Provider_][id$=error]").html("");
    

    The first line fires the validator which you will need for the rest of it. The second and third lines are the "official" way. The fourth line finds everything with the class "EditProv" and remove the "input-validation-error" from classes. Finally, the fifth line clears the error message text. For my form, the jquery validation plug in was adding or modifying this span:

    <span id="Provider_MedicareNum-error" class=""> 
    

    Where "Provider_MedicareNum" is the id of the element and jquery adds the -error to it.

    Dharman
    • 30,962
    • 25
    • 85
    • 135
    John
    • 819
    • 1
    • 9
    • 20
    0

    Try to use this for remove validation on the click on cancel

     function HideValidators() {
                var lblMsg = document.getElementById('<%= lblRFDChild.ClientID %>');
                lblMsg.innerHTML = "";           
                if (window.Page_Validators) {
                    for (var vI = 0; vI < Page_Validators.length; vI++) {
                        var vValidator = Page_Validators[vI];
                        vValidator.isvalid = true;
                        ValidatorUpdateDisplay(vValidator);
                    }
                } 
            }
    
    animuson
    • 53,861
    • 28
    • 137
    • 147