Taki
Taki

Reputation: 43

If jquery's form validation is ok, then I want to run a function before submitting the form

I'm using this to validate my form and it is fine:


    $(document).ready(function() {
        $("#myform").validate();
    });

But I need to run a function before the form submits but only if validation has passed. When I try to add the function after the validate, like this:


    $(document).ready(function() {
         $("#myform").validate();
         $('#submitButton').click(function() {
            ...
         });
    });

it runs even when the form fails validation.

I've also tried putting the validate function within the submitButton click and the same thing happens -- the function runs even if the form fails validation:


    $(document).ready(function() {
         $('#submitButton').click(function() {
            $("#myform").validate();
            ...
            ...
         });
    });

Upvotes: 4

Views: 2300

Answers (1)

alex
alex

Reputation: 490163

You can use a callback.

$("#myform").validate({
   submitHandler: function(form) {
     // do other stuff for a valid form
     form.submit();
   }
})

Source.

Upvotes: 7

Related Questions