I am trying to clear all error messages as well error highlighting when user click on the clear form
button, below are actual requirements
here is my code
$( document ).ready(function(){
var validator = $("#register_form").validate({
validator.resetForm();
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
For me, first 2 things are working, but when I am trying to clear complete form, I am not able to do this.this is how I am trying to clear it
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
}
But nothing is happening , though with $("#register_form")[0].reset();
, form fields are getting clear, but error messages are not getting cleared.
Quote OP:
1) Validate form using Jquery validation
You cannot put the validator.resetForm();
method inside of the .validate()
method.
.validate()
is a plugin method where the only thing that can go inside is a comma separated map of the allowed options, {option:value, option:value, etc.}
, as per the .validate()
method documentation.
resetForm()
method documentation
$("#register_form").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
cell: {
required: true
}
},
messages: {
// custom messages
}
});
.validate()
method DEMO: http://jsfiddle.net/P46gL/
Quote OP:
2) When user click on a field error message should be cleared (per field)
This is thanks to the focusCleanup
option. As you've already done, set it to true
and when you click on the field with an error, the error clears.
$("#register_form").validate({
focusCleanup: true,
rules: {
....
focusCleanup
DEMO: http://jsfiddle.net/P46gL/1/
Quote OP:
3) On clicking reset button, every error should be cleared
You would call the resetForm()
method from within a click
handler of the reset button. This will immediately remove all error messages from the entire form and reset the validation plugin to its initial state.
$('#clearform').on('click', function () {
$("#register_form").validate().resetForm(); // clear out the validation errors
});
Make sure the reset button is type="button"
or type="reset"
or it will trigger validation.
<input type="reset" id="clearform" value="reset form" />
Clear Errors DEMO: http://jsfiddle.net/P46gL/3/
Clearing out the field data
You can clear out the values of the fields by calling a JavaScript .reset()
like this.
$('#clearform').on('click', function () {
var form = $("#register_form");
form.validate().resetForm(); // clear out the validation errors
form[0].reset(); // clear out the form data
});
Full Working DEMO: http://jsfiddle.net/P46gL/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With