Vicky
Vicky

Reputation: 9585

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

Upvotes: 189

Views: 355407

Answers (30)

Hooman Bahreini
Hooman Bahreini

Reputation: 15559

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

Upvotes: 3

John
John

Reputation: 829

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.

Upvotes: 0

Eduardo Lucio
Eduardo Lucio

Reputation: 2477

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

Upvotes: 3

Codebricks
Codebricks

Reputation: 1253

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.

Upvotes: 0

user1892777
user1892777

Reputation: 151

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

Upvotes: 0

Sumit Kumar Gupta
Sumit Kumar Gupta

Reputation: 2364

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

Upvotes: 0

XWiśniowiecki
XWiśniowiecki

Reputation: 1843

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

Upvotes: 3

jlh
jlh

Reputation: 4677

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

Upvotes: 2

Artur Kedzior
Artur Kedzior

Reputation: 4263

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/

Upvotes: 2

jay
jay

Reputation: 1770

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

Upvotes: 0

mbadeveloper
mbadeveloper

Reputation: 1270

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

Upvotes: 2

Taras  Strizhyk
Taras Strizhyk

Reputation: 135

In my case helped with approach:

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

Upvotes: 1

kiran
kiran

Reputation: 71

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

This will destroy all the validation errors

Upvotes: 1

Parixit
Parixit

Reputation: 3855

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

Upvotes: 0

Abhijit Mazumder
Abhijit Mazumder

Reputation: 9464

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

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

Upvotes: 33

Parrots
Parrots

Reputation: 26892

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.

Upvotes: 231

michaelhsilva9944
michaelhsilva9944

Reputation: 65

I just did

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

to remove red border on the input error fields.

Upvotes: 1

Maximus
Maximus

Reputation: 2976

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

Upvotes: 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.

Upvotes: 0

shathar khan
shathar khan

Reputation: 1

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

Upvotes: 0

Brain Balaka
Brain Balaka

Reputation: 123

You can use:

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

Upvotes: 8

Travis J
Travis J

Reputation: 82297

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

    Upvotes: 143

  • Carrapicho
    Carrapicho

    Reputation: 122

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

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

    Upvotes: 6

    Trung
    Trung

    Reputation: 31

    I tested with:

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

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

    Upvotes: 3

    sad comrade
    sad comrade

    Reputation: 1501

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

    Upvotes: 5

    Meower68
    Meower68

    Reputation: 1009

    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.

    Upvotes: 21

    ZhukovRA
    ZhukovRA

    Reputation: 506

    Try to use:

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

    on Clear button.

    Upvotes: 0

    Juri
    Juri

    Reputation: 32920

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

    Upvotes: 52

    sunny goyal
    sunny goyal

    Reputation: 11

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

    Upvotes: 0

    Nick Craver
    Nick Craver

    Reputation: 630469

    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.

    Upvotes: 62

    Related Questions