我有这个验证功能:
var validator =$('#form1').validate({
ignore: "",
rules: {
usu_login: { required: true },
usu_email: { required: true },
usu_nombre1: { required: true },
usu_apellido1: { required: true },
usu_fecha_nac: { required: true },
usu_cedula: { required: true },
usu_telefono1: { required: true },
usu_password: {
required: function() { return focusout == true; }
},
usu_password2: {
required: function() { return focusout == true; }
},
usu_password3: {
required: function() { return focusout == true; },
equalTo: "#usu_password2"
}
}
}
我需要在if
函数中应用相同的equalTo
语句,这样可以按照我的意愿工作,但我不知道该怎么做。
答案 0 :(得分:2)
解决方案是使用规则的depends
属性!!!
jQuery(function ($) {
var focusout;
$('#state').change(function(){
focusout = this.checked;
}).change();
var validator = $('#myform').validate({
ignore: "",
rules: {
usu_login: {
required: true
},
usu_email: {
required: true
},
usu_nombre1: {
required: true
},
usu_apellido1: {
required: true
},
usu_fecha_nac: {
required: true
},
usu_cedula: {
required: true
},
usu_telefono1: {
required: true
},
usu_password: {
required: function () {
return focusout == true;
}
},
usu_password2: {
required: function () {
return focusout == true;
}
},
usu_password3: {
required: function () {
return focusout == true;
},
equalTo: {
depends: function(){
return focusout == true;
},
param: "#usu_password2"
}
}
},
messages: {}
});
});
演示:Fiddle
答案 1 :(得分:0)
你可以试试这个:
var rules = {
usu_login: { required: true },
usu_email: { required: true },
usu_nombre1: { required: true },
usu_apellido1: { required: true },
usu_fecha_nac: { required: true },
usu_cedula: { required: true },
usu_telefono1: { required: true },
usu_password: {
required: function() { return focusout == true; }
},
usu_password2: {
required: function() { return focusout == true; }
},
usu_password3: {
required: function() { return focusout == true; },
equalTo: "#usu_password2"
}
}
if (!focusout) {
for (key in rules) {
delete rules[key].equalTo;
}
}
var validator = $('#form1').validate({
ignore: "",
rules: rules
});
循环遍历所有规则并删除equalTo
约束,如果它应该被忽略。
但是,每次更改validator
时都必须重新创建focusout
对象。
答案 2 :(得分:0)
在您的情况下,您必须将自己的方法添加到验证器
$.validator.addMethod("mehod", function(value, element)
{
valid=false;
if(condition==true)//place your condition
{
valid=true;
}
else
{
valid=false;
}
return this.optional(element) || valid;
},"Your own error message");
并将其放在您要验证的位置
像这样:rules: {
usu_login: { required: true,method: true },//here you are using your method
usu_email: { required: true }
/*other rule*/
}
这适用于我的情况。