Search code examples
jqueryasp.net-mvcjquery-validateunobtrusive-validation

Cancel jquery button.click on MVC ValidationMessageFor


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?


Solution

  • 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.