JQuery validation messages only show up after multiple submits

前端 未结 2 1288
余生分开走
余生分开走 2020-12-21 13:49

I am trying to validate a form with the jquery-validate plugin. The html page doesn\'t show the error messages from the validation until I click submit twice. I know the s

相关标签:
2条回答
  • 2020-12-21 14:18

    You do not need to enclose it within the .submit() handler because the Validation Plugin takes care of that already. Please refer to the official demo page for working examples.

    $(document).ready(function() {
    
        $("form").validate({
            rules: {
                match: "required",
                limit: "required"
            },
            messages: {
                match: "Please enter a match"
            } // <- removed trailing comma
        });
    
    });
    

    BTW- you also had a trailing comma after the messages: options. Certain versions of IE would choke on that. This is the "Trailing Comma of Death" and it only affects certain versions of IE... other browsers' tools may not flag it as an error because it's technically not an error.


    A more detailed explanation of what was happening:

    Since you enclosed .validate() within .submit(), the Validation function does not even load until you hit submit. Since it's not already loaded when you hit submit, no validation will occur. Then when you hit submit the second time, the function is now loaded so it appears to work normally.

    When you enclose .validate() within document.ready, the Validation plugin loads immediately as the DOM is finished loaded. Therefore, it's ready and waiting for you to interact with your form and it behaves correctly on the first submit.

    0 讨论(0)
  • 2020-12-21 14:24

    I wouldn't advise using submit() as a means of activating form validation. Instead, use your submit button:

    $('input[type=submit]').click(function(event) {
       // Do your validation, if it fails use event.preventDefault(); 
    });
    
    0 讨论(0)
提交回复
热议问题