jQuery验证-两个字段,仅需填写一个 [英] jQuery Validation - Two fields, only required to fill in one
问题描述
我在表单上使用 jQuery验证插件.在我的表格上,我有一个电话"字段和一个手机号码"字段.
I'm using the jQuery Validation Plugin on my form. On my form I have a 'Telephone' field and a 'Mobile No.' field.
我该怎么做,以便用户必须填写其中一个,但可以是任一字段?
How would I go about making it so the user has to fill in one of them, but it can be either field?
推荐答案
这看起来就像您需要使用的依赖性回调
This looks like what you need to use dependency-callback
这将允许您执行以下操作:
What this will allow you to do is:
根据给定回调的结果,制作所需的元素.
Makes the element required, depending on the result of the given callback.
然后您可以在两个电话字段上放置一个required
验证规则,仅根据函数回调的返回值才需要此验证规则.因此,您可以在电话字段上放置一条规则,以说仅当移动字段为空白时才要求此规则,反之亦然.
You can then place a required
validation rule on the two telephone fields that will only be required based on the return from the function callback; thus you can put a rule on the telephone field to say require this rule only if the mobile field is blank, and vice versa for the mobile field.
这未经测试,但从理论上讲
This is untested but in theory
rules: {
telephone: {
required: function(element) {
return $("#mobile").is(':empty');
}
},
mobile: {
required: function(element) {
return $("#telephone").is(':empty');
}
}
}
请确保检查评论/其他答案以获取可能的更新答案.
更新
rules: {
telephone: {
required: '#mobile:blank'
},
mobile: {
required: '#telephone:blank'
}
}
这篇关于jQuery验证-两个字段,仅需填写一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!