[jquery] How to clear jQuery validation error messages?

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
    }
}

This question is related to jquery jquery-validate

The answer is


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.


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());

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);
                }
            } 
        }

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

$("#myForm").data('validator').resetForm();

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);

$(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.


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/

In my case helped with approach:

$(".field-validation-error span").hide();

I just did

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

to remove red border on the input error fields.


You can use:

$("#myform").data('validator').resetForm();

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).


var validator = $("#myForm").validate();
validator.destroy();

This will destroy all the validation errors


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");

Try to use:

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

on Clear button.


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.


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.


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');

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

$("#your_div").click(function() {
  $(".error").html('');
  $(".error").removeClass("error");
});

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


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();
    

  • 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 = {};
    

    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');
    

    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");
    
    }
    
    clearJqValidErrors($("#some_form_id"));
    

    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');
    

    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.


    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(); });
    

    I tested with:

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

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


    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');