jQuery validate plugin require field if another field has a value and vice versa

zaq picture zaq · May 2, 2012 · Viewed 61.6k times · Source

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?

Answer

Erico Chan picture Erico Chan · May 2, 2012

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()!="";
        }
}
....