How to fire jQuery function only if form is valid

前端 未结 2 1547
旧巷少年郎
旧巷少年郎 2020-12-01 04:51

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

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


        
相关标签:
2条回答
  • $(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.

    0 讨论(0)
  • 2020-12-01 05:43

    If you are using jquery validate unobtrusive validation you could:

    $(function () {
        $('#signupform').submit(function () {
            if($(this).valid()) {
                alert('the form is valid');
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题