Some of my forms require validation, for which I use the JQuery validation plug-in.
Some of my forms require a custom submit handler (which conditionally pops-up a c
$('#myform').validate({ // initialize the plugin
// your rules,
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
$("#myform").on('submit', function() {
alert("Real submit handler");
});
Your jsFiddle: http://jsfiddle.net/sferrari63/VGj2R/
Your submit
handler is firing every time the submit button is clicked even when the form is "invalid".
Quote OP:
This isn't what I would expect. I would think that validation would prevent both the submission and the submit handler from running. Am I doing something wrong, or are my expectations wrong?
You're doing something unnecessary and your expectations are wrong. Just because the jQuery Validate plugin is preventing the default submit action, does not mean that any external submit handlers will not fire.
This is the reason the developer gives you the submitHandler
and invalidHandler
callback functions. Since the plugin blocks default submit automatically, these callbacks replace the need for you to create submit
handler(s) of your own.
submitHandler
fires on click of the submit button only if/when the form is "valid".
invalidHandler
fires on click of the submit button only if/when the form is "invalid".
(Note: if your submit button contains class="cancel"
, the form will always evaluate as "valid" and the submitHandler
will always fire... all rules will be ignored. EDIT: class="cancel"
has since been deprecated in favor of the formnovalidate="formnovalidate"
attribute.)
If, for some odd reason, you need this additional submit
handler, you can test the form using the .valid()
method. Although, I don't recommend doing this when you already have perfectly good submit
handlers built into the plugin.
$("#myform").on('submit', function() {
if ($(this).valid()) {
alert("Form is valid");
}
});
DEMO: http://jsfiddle.net/VGj2R/1/
Since the plugin is handling the submit
event, it would be more correct to fire this code below on the button's click
handler instead.
$("#mySubmitButton").on('click', function() {
if ($("#myform").valid()) {
alert("Form is valid");
}
});
DEMO: http://jsfiddle.net/VGj2R/2/
However, unless your form does not have a submit button, the code above is unnecessary where the submitHandler
callback function can be used instead.