How to clear jQuery validation error messages?
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).
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.
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.
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:
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();