jQuery Validation need to execute same validation twice

亡梦爱人 提交于 2019-12-17 17:10:19

问题


I am working in a form which the user has to fill in two steps, first step he must give his name and email and in the second he must give his chosen password, so I have to execute a validation in the same form twice, it's succesful in the first step, but in the second it is just simple ignored and the form is being submited.

This is the js code:

jQuery(document).ready(function() {
      jQuery('#form_wk_new_user').submit(function() {
       if(jQuery('#form_wk_step_1').css('visibility') == 'visible') {

           jQuery('#form_wk_new_user').validate(
           {
            rules: {
                new_user_name: {
                    required: true
                },
                new_user_email: {
                    required: true,
                    email: true
                }
            },
            messages: {
                 new_user_name: {
                     required: 'requerido'
                 },
                 new_user_email: {
                      required: 'requerido',
                      email: 'correo no válido'
                 }   
            }
           }
         );
        if(jQuery('#form_wk_new_user').valid()) {
             jQuery('#form_wk_step_2').css('visibility','visible');
         }         
       }
       if(jQuery('#form_wk_step_2').css('visibility') == 'visible') {
             jQuery('#form_wk_step_1').css('visibility','hidden');
             jQuery('#form_wk_continue_btn').attr('value','Registrar');
             jQuery('#form_wk_new_user').validate(
                {
                 rules: {
                     new_user_pass: {
                         required: true
                     },
                     new_user_confirm_pass: {
                         required: true,
                         equalTo: '#new_user_pass'
                     }
                 },
                 messages: {
                      new_user_pass: {
                          required: 'requerido'
                      },
                       new_user_confirm_pass: {
                         required: 'requerido',
                         equalTo: 'contraseñas no coinciden'
                     }
                 }
                }

            );
           if(jQuery('#form_wk_new_user').valid()) {
            form.submit();
         }       
       } 
     return false; 
    });
});

And this is my form:

<form id="form_wk_new_user" method="post" action="">
    <div id="form_wk_step_1">
        <label>Nombre</label>
        <input type="text" id="new_user_name" name="new_user_name">
        <label>e-mail</label>
        <input type="text" id="new_user_email" name="new_user_email">
    </div>
    <div id="form_wk_step_2" style="visibility: hidden;">
        <label>Contraseña</label>
        <input type="password" id="new_user_pass" name="new_user_pass">
        <label>Confirma contraseña</label>
        <input type="password" id="new_user_confirm_pass" name="new_user_confirm_pass">
    </div>
    <div id="form_wk_continue"><input id="form_wk_continue_btn" type="submit" value="Continuar"></div>
</form>

回答1:


Your code (formatted for readability):

jQuery(document).ready(function() {

    jQuery('#form_wk_new_user').submit(function() {
       if (jQuery('#form_wk_step_1').css('visibility') == 'visible') {

           jQuery('#form_wk_new_user').validate({ // initialize plugin
               //options & rules
           });

           if(jQuery('#form_wk_new_user').valid()) {
               jQuery('#form_wk_step_2').css('visibility','visible');
           }         
       }
       if (jQuery('#form_wk_step_2').css('visibility') == 'visible') {
           jQuery('#form_wk_step_1').css('visibility','hidden');
           jQuery('#form_wk_continue_btn').attr('value','Registrar');
           jQuery('#form_wk_new_user').validate({ // initialize plugin
              //options & rules
           });
           if(jQuery('#form_wk_new_user').valid()) {
               form.submit();
           }       
       }
       return false; 
    }); // end submit handler

}); // end DOM ready

There is a fundamental misunderstanding here about how this plugin works. .validate() is only supposed to be called once on DOM ready to initialize the plugin. So by your code, the plugin is not even initialized until after the button is clicked and if the form is visible. It's never initialized on your second form since it's not yet visible when the button is clicked (your conditional logic fails and .validate() is never called). Even if you could fix this logical "catch-22", the new rules specified within the second .validate() cannot be applied in this fashion. After you call .validate() the first time, any rules must be added and removed via the rules('add') and rules('remove') methods. See this demo where the second call to .validate() has no effect.

Since the plugin has a built-in submitHandler callback function, it totally negates any need for wrapping anything within any other submit handler functions. (The callback is only fired for a valid form and as per documentation is "the right place to submit a form via Ajax after it validated.")

IMHO, this whole approach is unnecessarily messy and verbose, and should be replaced.

Instead of the same form with two different sets of inputs, which would require much more complex code to dynamically add & remove rules, you should simply use two different forms.

Something like this:

New jQuery:

jQuery(document).ready(function() {

    jQuery('#form_wk_new_user1').validate({ // initialize plugin on form 1
        // options & rules for form 1,
        submitHandler: function (form) {
            jQuery('#form_wk_step_1').hide(); // hide step 1
            jQuery('#form_wk_step_2').show(); // show step 2
            return false; // stop normal submit event
        }
    });

    jQuery('#form_wk_new_user2').validate({ // initialize plugin on form 2
        // options & rules for form 2,
        submitHandler: function (form) {
            var result1 = jQuery('#form_wk_new_user1').serialize(); // get the contents of form 1
            var result2 = jQuery(form).serialize(); // get the contents of form 2
            // your code to combine the data from form 1 with form 2
            // your code to submit form with data, ajax or other
            // return false; // block a page redirect if you use ajax
        }
    });

}); // end DOM ready

New HTML:

<form id="form_wk_new_user1">
    <div id="form_wk_step_1">
        <label>Nombre</label>
        <input type="text" id="new_user_name" name="new_user_name"/>
        <label>e-mail</label>
        <input type="text" id="new_user_email" name="new_user_email"/>
        <input id="form_wk_continue_btn" type="submit" value="Continuar"/>
    </div>
</form>
<form id="form_wk_new_user2">
    <div id="form_wk_step_2" style="display: none;">
        <label>Contraseña</label>
        <input type="password" id="new_user_pass" name="new_user_pass"/>
        <label>Confirma contraseña</label>
        <input type="password" id="new_user_confirm_pass" name="new_user_confirm_pass"/>
        <input id="form_wk_continue_btn" type="submit" value="Registrar"/>
    </div>
</form>

Working Demo: http://jsfiddle.net/rNM4v/



来源:https://stackoverflow.com/questions/14990198/jquery-validation-need-to-execute-same-validation-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!