jQuery Validate插件,两个字段之一为必填项 [英] jQuery Validate plugin, one out of two fields is required
问题描述
我有一个包含2个字段的表格;手机号码.和电话号码.
I have a form with 2 fields; mobile no. and telephone no.
至少必须填写一个字段,但也可以填写两个字段.
at least 1 of the fields has to be filled in, but both can also be filled.
如果其中一个都不被填充,我需要jquery validate抛出错误.
I need jquery validate to throw an error if none of them are filled only.
我通过以下方式实现了这一目标:
I have achieved this with:
rules: {
mobile:{
required: {
depends: function(element) {
return $("#regTelephone").val() === '';
}
}
},
telephone:{
required: {
depends: function(element) {
return $("#regMobile").val() === '';
}
}
}
}
但是,如果只有一个字段为空,则此字段仍将获得有效"类,我不希望这样做,因为我的有效CSS具有绿色边框(因此,空白字段仍具有绿色边框)
however, if only one field is empty, this field still gets the 'valid' class, which I don't want as my valid css has a green border (so the empty field still gets a green border)
所以:我如何获取为空的字段(假设另一个字段具有值)而不获取有效的类,因此没有绿色边框?
so: how do I get the field which is empty (providing the other has a value) to not get the valid class and therefore the green border?
推荐答案
使用可选的additional-methods.js
文件,有一种名为require_from_group
的方法可以完全满足您的要求. (您必须至少使用插件的 版本1.11.1以避免过去的错误.)
Using the optional additional-methods.js
file, there is a method called require_from_group
that does exactly what you request. (You must use at least version 1.11.1 of the plugin in order to avoid a past bug.)
rules: {
mobile:{
require_from_group: [1, '.mygroup']
},
telephone:{
require_from_group: [1, '.mygroup']
}
},
....
1
参数是该组中需要多少个参数.在HTML标记中,组中的字段必须包含与第二个参数中指定的class
匹配的class
.
The 1
parameter is how many from the group are required. In the HTML markup, the fields in your group must contain a class
matching the class
specified in your second parameter.
<input type="text" class="mygroup" name="mobile" />
<input type="text" class="mygroup" name="telephone" />
工作演示: http://jsfiddle.net/NfcxX/
我的演示还显示了groups
选项,该选项将多个错误消息组合为一个.
My demo also shows the groups
option which combines the multiple error messages into one.
这篇关于jQuery Validate插件,两个字段之一为必填项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!