我正在尝试根据提交的信息获取表单进行验证。如果我需要所有字段,那么一切正常,但是当我在需求上加上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
}
},
});
感谢您的帮助!
答案 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
}
},
});