AJAX and jQuery validate issue

后端 未结 1 1207
我寻月下人不归
我寻月下人不归 2021-01-28 04:39

So I got stuck in this dead end. I have AJAX script and jQuery Validation plug-in. With this script, when my page loads empty contact form automatically submits on itself. If I

相关标签:
1条回答
  • 2021-01-28 05:01

    Your ajax is running on page load because nothing is stopping it. You need to put the ajax code inside an event handler so it's only called if/when your form passes validation.

    The following is an example of the proper implementation of the Validation Plugin. And you do not need to put the validate() inside a click handler. The Validation plugin has a bunch of its own handlers built in including a submitHandler that fires when the form passes validation.

    <script type='text/javascript'>
    
    $(document).ready(function() {
    
        jQuery.validator.addMethod("math",
            function(value, element, params) { return this.optional(element) || value == params[0] + params[1]; },
            jQuery.format("Please enter the correct value for {0} + {1}")
        );
    
        $('form').validate({
            rules {
                // your rules
            },
            submitHandler: function(form) {
                $.ajax({
                    // your ajax parameters
                });         
                return false;
            }
        });
    
    });
    
    </script>
    

    Validation Plugin Documentation

    Some side issues...

    1. Your code would be much easier to read & troubleshoot if you used proper indentation and standard formatting.

    2. There is not need to use duplicate document.ready functions. Everything can be inside one.

    3. Like in #2, you do not need separate sets of <script></script> tags to contain your code. Everything can be enclosed once.

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