Wednesday, December 1, 2010

JQuery Validate dependency-expressions for custom rules

JQuery Validate has a nice feature that allows you to specify dependency-expression that must hold for rule to kick in. For example standard 'required' rule might accept expression like this:
$("#myForm").validate({
rules: {
myTextbox: {
required: "#myCheckbox:checked"
}
}
});
This tells 'required' rule that it should be used only when myCheckbox is checked. However'required' is the only rule that comes out of box with an option to specify a condition under which it works. What should you do in case you need to make your own rule use dependency-expression?

To enable depedency behavior for a custom rule use the following code:

jQuery.validator.addMethod("greaterThanZero", function(value, element, param) {
if ( !this.depend(param, element) )
return "dependency-mismatch";
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
The if statement here does the trick. It checks if dependecy-expression is satisfied before proceeding to validation. Build in 'required' rule is actually using the same mechanism.