如何在 jQuery 验证插件的多个字段中添加 'depends:' 规则?
How to add 'depends:' rule to many fields in jQuery validation plugin?
我已经使用这个规则来验证用户的帐单地址,如果他想要一个账单(检查输入#billyes),这是我当前的代码:
//BILLING VALIDATION
legal_id: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
},
billing_name: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
},
billing_adress: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
},
.... ETC
return $('#billyes').is(":checked");
行也重复了
我想做这样的事情:
//BILLING VALIDATION
legal_id,billing_name,billing_adress,etc: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
}
这可能吗?还有其他选择吗?
谢谢。
legal_id,billing_name,billing_adress,etc: {
在 .validate()
方法中,您 不能 做任何类似的事情。 rules
选项中的对象文字必须是 key:value
对,其中 key
只能是单个字段 name
.
但是,有一种方法可以同时将相同的规则应用于多个字段:
您可以将 .rules()
方法与 jQuery .each()
结合使用。但是您需要一个聪明的 jQuery 选择器来同时定位它们。就像 "starts with" 选择器或 class
。您不能使用 "starts with billing_
",因为您还有 legal_id
,因此您需要为这些字段分配 class
或执行其他操作。
$('.yourFields').each(function() {
$(this).rules('add', {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
});
});
否则不行,.validate()
方法内部,没有捷径
我已经使用这个规则来验证用户的帐单地址,如果他想要一个账单(检查输入#billyes),这是我当前的代码:
//BILLING VALIDATION
legal_id: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
},
billing_name: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
},
billing_adress: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
},
.... ETC
return $('#billyes').is(":checked");
我想做这样的事情:
//BILLING VALIDATION
legal_id,billing_name,billing_adress,etc: {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
}
这可能吗?还有其他选择吗?
谢谢。
legal_id,billing_name,billing_adress,etc: {
在 .validate()
方法中,您 不能 做任何类似的事情。 rules
选项中的对象文字必须是 key:value
对,其中 key
只能是单个字段 name
.
但是,有一种方法可以同时将相同的规则应用于多个字段:
您可以将 .rules()
方法与 jQuery .each()
结合使用。但是您需要一个聪明的 jQuery 选择器来同时定位它们。就像 "starts with" 选择器或 class
。您不能使用 "starts with billing_
",因为您还有 legal_id
,因此您需要为这些字段分配 class
或执行其他操作。
$('.yourFields').each(function() {
$(this).rules('add', {
required: {
depends: function(element) {
return $('#billyes').is(":checked");
}
}
});
});
否则不行,.validate()
方法内部,没有捷径