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
}
}
Solution 1:
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:
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();
Solution 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.
Solution 4:
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).