Reputation: 1646
I have an MVC solution that is using @Html.ValidationMessageFor along with a $('.btn').click() function to display a simple "Loading..." dialog. I would like to cancel this click() function action if the form validation fails. I have looked into the jquery.validation.unobtrusive library (and included it in my solution) and am currently attempting to do a check as follows.
$('.btn').click(function () {
if ($(this).validate().valid()) {
$("#initialWaitTableLoad").fadeIn();
}
});
This validation check does not work and is still executing the fadeIn() method. How can I prevent this action from occurring on validation failure?
Upvotes: 0
Views: 459
Reputation: 98718
If you need to check a form's validity when a button is clicked, you would use the .valid()
method within your click handler and attach .valid()
to your form
, not the button, as you had done.
$('.btn').click(function () {
if ($('#myform').valid()) { // test validity of the form
$("#initialWaitTableLoad").fadeIn();
}
});
EDIT:
$('#myform')
is simply my generic example above. Inspect the DOM and use whatever jQuery selector you wish that targets this particular form.
Upvotes: 2
Reputation: 6831
You need to check for validity on the form, not the button. In your case $(this) is referring to the button that was just clicked. If possible, edit your function to run on form submission rather than button click.
$('#myform').submit(function () {
if ($(this).valid()) {
$("#initialWaitTableLoad").fadeIn();
}
});
Upvotes: 1