How to fire jQuery function only if form is valid
Asked Answered
I

2

55

I have a jQuery function tied to my submit button like this:

$(function () {
    $('#signupform').submit(function () {
        alert('test');
    });
});

However, it fires whether or not the form is valid. My model is decorated with various DataAnnotations and the client-side validation is working well, but I only want that jQuery function to fire if the form has been validated. How do I accomplish that?

EDIT: To clarify, I'm using MVC DataAnnotations + jQuery's unobtrusive javascript to handle the client-side validation. I do not have my own javascript validation routines written. The built in jQuery validation is doing a great job of validating the form, but I just need to know how to get the results of that validation into a boolean value within my own function.

Impress answered 19/2, 2011 at 17:24 Comment(0)
C
132

If you are using jquery validate unobtrusive validation you could:

$(function () {
    $('#signupform').submit(function () {
        if($(this).valid()) {
            alert('the form is valid');
        }
    });
});
Celibacy answered 19/2, 2011 at 17:31 Comment(3)
To avoid form submitting twice add event.preventDefault(); check this and this , hope helps some one.Academicism
how come valid() is not defined when I have included "~/Scripts/jQueryValidator1.11/jquery.validate.js"Muire
@shaijut, I know this is an old comment, but just to note that the examples you cite are doing work on the button click event. I don't think the double submit is an issue when you are using the form submit eventAberration
U
8
$(function () {
    $('#signupform').submit(function (e) {
        if (validateForm() === true) {
            alert('Form is valid.');
        }
    });
});

Note, the validateForm() function would be the one you use within the browser to test validation. EDIT: This is indeed jQuery's $(this).valid().

NOTE: On clarification of the question, the answer above is one way to stop form submitting on validation, but not the technique that was desired (jQuery valid() validation). See Darin Dimitrov's answer for details.

Also, on rereading the original question, the intent was the exact opposite of what I originally described. So I edited to demonstrate a functional response on validation, not how to prevent submitting a form.

Uyekawa answered 19/2, 2011 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.