How can I use jQuery.validate without submitting the form?

前端 未结 1 920
傲寒
傲寒 2020-12-05 19:48

I have read several of the other posts about this and still no go. Trying to keep it real simple. I need to validate sections of a form that are being hidden/shown in a jQue

相关标签:
1条回答
  • 2020-12-05 20:39

    The problem is that you cannot initialize validate() inside a handler. You initialize it inside the document.ready and use .valid() to test for validity. A submit button is not required to validate the form in this case.

    As per this answer:

    .validate() is what initializes the Validation plugin on your form.

    .valid() returns true or false depending on if your form is presently valid.

    So within your .click() handler, you'd use .valid(), not .validate(), in conjunction with an if statement to test if form is valid...

    $(document).ready(function() {
        $("#test").validate({  // initialize plugin on the form
             rules: {
             ...
             }
             ...
             // etc.
        });
    
        $(".next").click(function(){  // capture the click
            if($("#test").valid()){   // test for validity
                // do stuff if form is valid
            } else {
                // do stuff if form is not valid
            }
        });
    });
    

    See docs.jquery.com/Plugins/Validation/valid for more info.

    Normally, you would have a type="submit" button within the form container and, in that case, would not need to capture any clicks as this is all done automatically. This answer is tailored for the OP's specific case where a traditional submit button is not used.

    Side-note: All of your JavaScript can be contained within a single set of <script></script> tags. Multiple sets of tags all strung together is unnecessary and superfluous.

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