我正在尝试获取一个表格,以基于提交的信息进行验证。如果我将所有字段都设为必填项,则一切正常,但只要在需求中加入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
                }
       },

    });


谢谢您的帮助!

最佳答案

我通常使用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;
                        }
                     }
            }
   }

});

关于javascript - jQuery form.validate有条件的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34885583/

10-11 10:47