jquery form.validate条件必需

时间:2016-01-19 19:43:05

标签: javascript jquery validation

我正在尝试根据提交的信息获取表单进行验证。如果我需要所有字段,那么一切正常,但是当我在需求上加上if语句时,我的验证不起作用。

不起作用:

var form = $( "#send_request_sms" );
    form.validate({
       rules: {
           first_name: { 
             required: true 
           } , 
               last_name: { 
               required: true 
           },              
                        mobile: { 
               required: $('#email').val() ? false : true
           },   
                email: {
                    required: $('#mobile').val() ? false : true
                }
       },

    }); 

工作正常:

var form = $( "#send_request_sms" );
    form.validate({
       rules: {
           first_name: { 
             required: true 
           } , 
               last_name: { 
               required: true 
           },              
                        mobile: { 
               required: true
           },   
                email: {
                    required: true
                }
       },

    }); 

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

我通常使用depends并在我的情况下工作

var form = $( "#send_request_sms" );
form.validate({
   rules: {
       first_name: { 
         required: true 
       } , 
       last_name: { 
           required: true 
       },              
        mobile: { 
           required: {depends: function(element) {
                         return jQuery("#email").val() == '' ? true : false;
                        }
                     }
              },   
            email: {
                required: {depends: function(element) {
                        return jQuery("#mobile").val() == '' ? true : false;
                        }
                     }
            }
   }

}); 

答案 1 :(得分:0)

我建议将条件语句移到validate对象之外。

e.g。

var form = $("#send_request_sms");
var mobileRequired = $('#email').val() ? false : true;
var emailedRequired = $('#mobile').val() ? false : true;
form.validate({
   rules: {
       first_name: { 
         required: true 
       }, 
       last_name: { 
         required: true 
       },              
       mobile: { 
         required: mobileRequired
       },   
       email: {
         required: emailRequired
       }
   }
}); 

答案 2 :(得分:0)

我认为你错过了电子邮件和手机的订单

var form = $( "#send_request_sms" );
form.validate({
   rules: {
       first_name: { 
         required: true 
       } , 
       last_name: { 
           required: true 
       },              
       mobile: { 
           required: $('#mobile').val() ? false : true
       },   
       email: {
           required: $('#email').val() ? false : true
       }
   },

});