validate

 

Adding jQuery validation rules is one of the things that makes it my choice for client-side validation. There are lots of rules built into the plugin out of the box and you can add a new validation rule method easily. Occasionally however, whether a field is required, is dependent upon either the value of another field element, if a particular radio button or dropdown entry is selected or a checkbox is checked. For example an address may only be required if the send me the newsletter by post checkbox has been checked.

jQuery validation rules - depends

Fortunately the jQuery validation plugin allows for such occurences. To make a field only required if another field meets a certain criteria we use "depends" in the following way:

rules: {
address: {
required: {
depends: function(element) {
if ($('#newsletterByPost').is(':checked')){
return true;
}else{
return false;
}
}
}
}
}

As you can see we have our rules object which has the rule for the address field. required:true is how we do it to make the field always required. For a depends rule we simply add a depends which contains a conditional to find out if the checkbox has been checked. This is just a short example of how jQuery Validation rules work in conjunction with depends. There is literally no limit to the number of fields that are checked, you just need to make sure the returned value of the function returns a boolean value i.e. true or false.