Interaction between JQuery validation and form submit handler: Broken, or am I doing something wrong?

后端 未结 1 495
盖世英雄少女心
盖世英雄少女心 2020-12-06 23:54

Some of my forms require validation, for which I use the JQuery validation plug-in.

Some of my forms require a custom submit handler (which conditionally pops-up a c

相关标签:
1条回答
  • 2020-12-07 00:26
    $('#myform').validate({ // initialize the plugin
        // your rules,
        submitHandler: function (form) { 
            alert('valid form submitted');
            return false;
        }
    });
    
    $("#myform").on('submit', function() {
        alert("Real submit handler");
    });
    

    Your jsFiddle: http://jsfiddle.net/sferrari63/VGj2R/

    Your submit handler is firing every time the submit button is clicked even when the form is "invalid".

    Quote OP:

    This isn't what I would expect. I would think that validation would prevent both the submission and the submit handler from running. Am I doing something wrong, or are my expectations wrong?

    You're doing something unnecessary and your expectations are wrong. Just because the jQuery Validate plugin is preventing the default submit action, does not mean that any external submit handlers will not fire.

    This is the reason the developer gives you the submitHandler and invalidHandler callback functions. Since the plugin blocks default submit automatically, these callbacks replace the need for you to create submit handler(s) of your own.

    • submitHandler fires on click of the submit button only if/when the form is "valid".

    • invalidHandler fires on click of the submit button only if/when the form is "invalid".

    (Note: if your submit button contains class="cancel", the form will always evaluate as "valid" and the submitHandler will always fire... all rules will be ignored. EDIT: class="cancel" has since been deprecated in favor of the formnovalidate="formnovalidate" attribute.)

    If, for some odd reason, you need this additional submit handler, you can test the form using the .valid() method. Although, I don't recommend doing this when you already have perfectly good submit handlers built into the plugin.

    $("#myform").on('submit', function() {
        if ($(this).valid()) {
            alert("Form is valid");
        }
    });
    

    DEMO: http://jsfiddle.net/VGj2R/1/

    Since the plugin is handling the submit event, it would be more correct to fire this code below on the button's click handler instead.

    $("#mySubmitButton").on('click', function() {
        if ($("#myform").valid()) {
            alert("Form is valid");
        }
    });
    

    DEMO: http://jsfiddle.net/VGj2R/2/

    However, unless your form does not have a submit button, the code above is unnecessary where the submitHandler callback function can be used instead.

    0 讨论(0)
提交回复
热议问题