How to clear jQuery validation error messages?

Viewed 325322

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

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.

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.

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

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/

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

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

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

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

This will destroy all the validation errors

In my case helped with approach:

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

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.

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

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

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

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.

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.

Related