问题
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?
回答1:
if you look at the "rules" section's example code in the documentation page, there is a depends field you can set.
something like the following (this is right off my head, not tested):
...
secondInput: {
required: function(element){
return $("#firstInput").val()!="";
}
}
....
回答2:
Just for clarification this is what I ended up doing based on Erico's answer:
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.
来源:https://stackoverflow.com/questions/10406089/jquery-validate-plugin-require-field-if-another-field-has-a-value-and-vice-versa