jQuery验证需要执行两次相同的验证 [英] jQuery Validation need to execute same validation twice

查看:61
本文介绍了jQuery验证需要执行两次相同的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作方式是用户必须填写两个步骤,第一步,他必须提供其姓名和电子邮件,第二步,必须输入其选择的密码,因此我必须以相同的形式执行验证两次,第一步就成功了,但是在第二步中,它只是简单地被忽略了,正在提交表单.

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.

这是js代码:

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; 
    });
});

这是我的表格:

<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>

推荐答案

您的代码(为便于阅读而设置):

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

关于此插件的工作原理,这里有一个基本的误解. .validate() 仅应被称为一次在DOM上可以初始化插件.因此,通过您的代码,甚至在单击按钮之后并且表单可见后,插件才被初始化.从未在第二种形式上对其进行初始化,因为在单击按钮时它尚不可见(您的条件逻辑失败,并且从未调用.validate()).即使您可以修复此逻辑"catch-22",也不能以这种方式应用第二个.validate()中指定的新规则.首次调用.validate()后,必须通过rules('add')rules('remove')方法添加和删除所有规则. 查看此演示,其中第二次调用.validate()无效.

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.

由于该插件具有内置的submitHandler回调函数,因此完全不需要在任何其他submit处理函数中包装任何内容. (仅针对有效格式触发回调,并且根据文档 验证后通过Ajax提交表单的正确位置." )

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.

代替带有两个不同输入集的同一个form,这将需要更复杂的代码来动态添加&删除规则,您只需使用两种不同的形式.

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.

类似这样的东西:

新版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

新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>

工作示例: http://jsfiddle.net/rNM4v/

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

这篇关于jQuery验证需要执行两次相同的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆