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 markup




Javascript

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


Other Blogs

Getting Started with the Telerik MVC Extensions - 2/12/2012
Codemash 2012 Recap & Pictures - 1/14/2012
Findlay Area .Net Users Group(FANUG) - Improving Software Quality with Continuous Integration, and An Introduction to FluentMigrator - 9/28/2011
MVC3 Unobtrusive Validation With MVC Contrib - 8/14/2011
Automating SSRS Report Deployment for CI - 7/10/2011