jQuery validate - set conditional rules based on user selection
jQuery validate with condition as a function result (adding on to Ryley's comment above):
$("#Form_Id").validate({
rules: {
CompletedBy: "required", //straight forward validation of field
Contact_No: "required",
Location: { required: noTableRow }//if no table row, make Location mandatory
}
});
//checks whether a table row exists
function noTableRow() {
return $("tr.tr_class").length == 0;
}
You can use a custom validation method. For example:
jQuery.validator.addMethod("checkA", function(value, element) {
return YourValidationCode; // return true if field is ok or should be ignored
}, "Please complete A");
then use it in your rules:
rules: {
....
field_a: {
required: false,
checkA: true
},
....
}
Take a look: http://jqueryvalidation.org/jQuery.validator.addMethod/
jQuery Validate actually directly supports this, using dependency expressions.
All you need to do is change your validate options like this:
$('#myform').validate({
rules: {
fieldA: {
required:'#checkA:checked'
}
}
});
That's it!