How to clear jQuery validation error messages?

JqueryJquery Validate

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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();
    
  • Solution 3 - Jquery

    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.

    Solution 4 - Jquery

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

    Solution 5 - Jquery

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

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

    Solution 6 - Jquery

    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.

    Solution 7 - Jquery

    You can use:

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

    Solution 8 - Jquery

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

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

    Solution 9 - Jquery

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

    Solution 10 - Jquery

    I tested with:

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

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

    Solution 11 - Jquery

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

    Solution 12 - Jquery

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

    Solution 13 - Jquery

    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/
    

    Solution 14 - Jquery

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

    Solution 15 - Jquery

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

    This will destroy all the validation errors

    Solution 16 - Jquery

    In my case helped with approach:

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

    Solution 17 - Jquery

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

    Solution 18 - Jquery

    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

    Solution 19 - Jquery

    Try to use:

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

    on Clear button.

    Solution 20 - Jquery

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

    Solution 21 - Jquery

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

    Solution 22 - Jquery

    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.

    Solution 23 - Jquery

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

    Solution 24 - Jquery

    I just did

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

    to remove red border on the input error fields.

    Solution 25 - Jquery

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

    Solution 26 - Jquery

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

    Solution 27 - Jquery

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

    Solution 28 - Jquery

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

    Solution 29 - Jquery

    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.

    Solution 30 - Jquery

    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.

    Attributions

    All content for this solution is sourced from the original question on Stackoverflow.

    The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

    Content TypeOriginal AuthorOriginal Content on Stackoverflow
    QuestionVickyView Question on Stackoverflow
    Solution 1 - JqueryParrotsView Answer on Stackoverflow
    Solution 2 - JqueryTravis JView Answer on Stackoverflow
    Solution 3 - JqueryNick CraverView Answer on Stackoverflow
    Solution 4 - JqueryJuriView Answer on Stackoverflow
    Solution 5 - JqueryAbhijit MazumderView Answer on Stackoverflow
    Solution 6 - JqueryMeower68View Answer on Stackoverflow
    Solution 7 - JqueryBrain BalakaView Answer on Stackoverflow
    Solution 8 - JqueryKarra MaxView Answer on Stackoverflow
    Solution 9 - Jquerysad comradeView Answer on Stackoverflow
    Solution 10 - JqueryTrungView Answer on Stackoverflow
    Solution 11 - JquerySebastian Xawery WiśniowieckiView Answer on Stackoverflow
    Solution 12 - JquerymbadeveloperView Answer on Stackoverflow
    Solution 13 - JqueryArtur KędziorView Answer on Stackoverflow
    Solution 14 - JqueryEduardo LucioView Answer on Stackoverflow
    Solution 15 - JquerykiranView Answer on Stackoverflow
    Solution 16 - JqueryTaras StrizhykView Answer on Stackoverflow
    Solution 17 - JqueryjlhView Answer on Stackoverflow
    Solution 18 - JqueryHooman BahreiniView Answer on Stackoverflow
    Solution 19 - JqueryZhukovRAView Answer on Stackoverflow
    Solution 20 - Jquerysunny goyalView Answer on Stackoverflow
    Solution 21 - Jqueryshathar khanView Answer on Stackoverflow
    Solution 22 - Jquerypeter the programming godView Answer on Stackoverflow
    Solution 23 - JqueryMaximusView Answer on Stackoverflow
    Solution 24 - Jquerymichaelhsilva9944View Answer on Stackoverflow
    Solution 25 - JqueryParixitView Answer on Stackoverflow
    Solution 26 - JqueryjayView Answer on Stackoverflow
    Solution 27 - JquerySumit Kumar GuptaView Answer on Stackoverflow
    Solution 28 - Jqueryuser1892777View Answer on Stackoverflow
    Solution 29 - JqueryStephen GarsideView Answer on Stackoverflow
    Solution 30 - JqueryJohnView Answer on Stackoverflow