Conditional Validation with jQuery Validate - 3/21/2011
In 90% of scenarios, fields that are required are always required. However, in some cases, you may only want to apply validation if some other form field has a specific value. For example, you may want a "please explain" box to be required only if a user selected "other" in a drop down list. These types of rules cannot be statically coded.
Adding Validation Rules Dynamically
Unless you have read the documentation in depth, you may not have known that you can add jQuery validation rules after a page is loaded and validation is configured. For example, if you want a textbox to be required only if a corresponding checkbox is checked
HTML markupJavascript
Conditionally Applying Validation Rules
Using a trick I recently discovered, the above code can be greatly simplified. Where required is set to true or false on line 5 above, a selector can be used.
$(document).ready(function() {
$("#otherExplanation").rules("add", {
required: $("#checkbox1").is(':checked'),
messages: {
required: "Other Explanation is Required"
}
});
});
As you can see, in line 3 of this example, required is not set to an absolute value of true or false. Any jQuery selector that returns a boolean can be used. Thus you could check if a panel is visible, if a value is selected in a drop down list, etc.
Share this article
Leave a Comment