Using jQuery Validate, is there a way to determine if a form is valid without revalidating the form.
Per this question on how to add a 'submitHandler' function when using jQuery Unobtrusive Validation?, I'm listening to the invalid-form.validate
event to show the user a custom error when the form has been validated and has errors.
Per this question on how to prevent double click on submit, I'm disabling the submit button once the form has been submitted, but only if the form is valid, so the user can take corrective action and resubmit once the form is cleaned up.
The problem is now invalid-form.validate
fires twice.
Since the invalid-form.validate
event fires before my form submission handler, I'll already know the number of errors. Does the .valid()
method persist the number of errors somewhere that I can check against that value instead of revalidating the form.
Here's an example in stack snippets. Hit submit before filling in the required fields and you'll see two error messages.
$("form").validate();
// show message on invalid submission
$("form").on("invalid-form.validate", function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
alert('There is a problem with ' + errors + ' fields.');
}
});
// prevent double click form submission
$('form').submit(function () {
if ($(this).valid()) {
$(':submit', this).attr('disabled', 'disabled');
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<form >
<input type="text" name="Name" required /><br/>
<input type="text" name="Email" required /><br/>
<input type="submit" value="Submit"/>
</form>
I could save them to the the element in my invalid-form.validate
, but this won't update when the form is valid and also couples my double click code very heavily with my custom error code. If I take out the custom error code at some later date, I'll have to rewrite the double click prevention.
Any ideas?
You can use below code to check form is valid without triggering UI
Instead of attaching an extra listener to the form submit, you can use the
submitHandler
:The default function behaves like this:
Just pass in a
submitHandler
tovalidate()
and add the code to disable the button like this:Just be careful doing anything to the form inside of the
submitHandler
callback because it's easy to trigger a case of infinite recursionHere's a demo in Stack Snippets: