How do I get my jQuery Validator Code to run a second time after a form has already been submitted?

后端 未结 1 803
孤城傲影
孤城傲影 2020-12-04 02:52

Here is the scenario.

A user fills out a form. He forgets some required info. My validation code indicates to the user the missing field is required. He fills out th

相关标签:
1条回答
  • 2020-12-04 03:40

    Your problem is totally with your implementation.

    The following occurs when the page loads which makes your form work sucessfully on the first submit...

    var validator = form.validate({
        rules: {
            Author: "required",
    
            etc....
    

    Then, because you've enclosed it again within a submit handler, it's reinitialized here...

    form.live('submit', function (e) {
        e.preventDefault(); //Prevent Browser from getting new url
    
        $(this).validate();
    

    ... which breaks it for the next submit.

    All you need to do is initialize it once (including all the options) and not inside a submit handler...

    $('#CommentsForm').validate({
        rules: {
            Author: "required",
    
            etc....
    

    Refer to the source code of these official demos.


    EDIT:

    Again, you do not need a submit handler as it's interfering with your form submission.

    In other words, your validation is working fine but when you hit "submit", your external submit handler function takes over completely so it's no wonder that validation then starts failing.

    As I mentioned in my original comments, the Validation plugin has a submit handler built in to handle everything including your ajax.

    Remove all this completely...

    form.live('submit', function (e) { ....
    

    Then inside your validate() function, you'd simply add a submit handler as per the plugin documentation listed as the second option...

    $('#CommentsForm').validate({
        rules: {
            Author: "required",
    
            /// etc....
    
        },
    
        submitHandler: function(form) {
    
            /// put all your ajax and such in here
    
        }
    
     });
    
    0 讨论(0)
提交回复
热议问题