如果另一个字段有值,则 jQuery 验证插件需要字段,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10406089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery validate plugin require field if another field has a value and vice versa
提问by zaq
I am using the jQuery validate plugin to validate my form. I would like to tie several pairs of fields together such that if one field has a value, the other is required to have a value also. Essentially both fields (both text inputs) must either both have a value or both not have a value. Is anyone aware of a good way to accomplish this?
我正在使用 jQuery 验证插件来验证我的表单。我想将几对字段绑定在一起,这样如果一个字段有一个值,另一个字段也需要有一个值。本质上,两个字段(两个文本输入)必须要么都具有值,要么都没有值。有没有人知道实现这一目标的好方法?
回答by Erico Chan
if you look at the "rules" section's example code in the documentation page, there is a depends
field you can set.
如果您查看文档页面中“规则”部分的示例代码,depends
您可以设置一个字段。
something like the following (this is right off my head, not tested):
类似于以下内容(这是我的想法,未经测试):
...
secondInput: {
required: function(element){
return $("#firstInput").val()!="";
}
}
....
回答by zaq
Just for clarification this is what I ended up doing based on Erico's answer:
只是为了澄清,这是我最终根据 Erico 的回答所做的:
firstInput: {
required: function(element){
return $("#secondInput").val().length > 0;
}
},
secondInput: {
required: function(element){
return $("#firstInput").val().length > 0;
}
}
Each input is now dependent on the other and will only be required if the other has a value.
每个输入现在都依赖于另一个,并且只有在另一个有值时才需要。
回答by Kalpesh Parikh
If you want to validate without plugin
如果您想在没有插件的情况下进行验证
if ((field1 && !field2) || (!field1 && field2)) {
// error message
}