jQuery disable rule validation on a single field

I am using MVC to create forms that are generated at runtime. For validation, I am trying my hand at the jQuery validation library which is very convenient to use. I have the validation expression of each field in the cdata attribute of the tag

<input type="text" name="xyz" id="xyz" class="defaultTextBox"
  cdata="{validate:{required:true, decimal:true, messages:
          {required:'Please enter an decimal value', 
           decimal:'Please enter a valid decimal'}}}">

This works beautifully. Now one more requirement I have is that some fields are being shown and hidden according to the logic on the page and I need to disable the validation on the hidden fields such that they do not interfere with the form submission. Just toggling the required:true to false and back to true should be enough. Only i do not know how.

Anyone has any experience with that?


Solution 1:

Just add the ignore rule and define the selector. In this example, the validation will ignore all elements that have the class="ignore"

$("#myform").validate({
   ignore: ".ignore"
})

Solution 2:

If you're using ASP.NET MVC Unobtrusive JQuery validation you need to set the settings in this way. This is because of the way Microsoft actually calls jQuery validate. This should be safe to do inside a ready method.

Edit: Please see Cory's comment below before copy pasting this. This is my original code

    $("form").data("validator").settings.ignore = ".data-val-ignore, :hidden, :disabled";

Then I just apply .data-val-ignore class to things not to validate.

Note that you'll probably want to add :hidden which is actually the default ignore behavior defined in jquery.validate.js. I like to add :disabled too.

$.extend($.validator, {
defaults: {
    messages: {},
    groups: {},
    rules: {},
    errorClass: "error",
    validClass: "valid",
    errorElement: "label",
    focusInvalid: true,
    errorContainer: $([]),
    errorLabelContainer: $([]),
    onsubmit: true,
    ignore: ":hidden",              // default for ignore in jquery.validate.js
    ignoreTitle: false,
    onfocusin: function( element, event ) {
        this.lastActive = element;

And finally you may want to style it - especially useful during debugging.

.data-val-ignore
{
    background: #eee;
}

Solution 3:

Following on Gabe's answer, you can also set the ignore value as a default, so you don't have to set it on each form.

$.validator.setDefaults({ignore: ".ignore"});

Also note, the ignore field is a jQuery selector that is used in the jQuery not() function so any valid selector can be used, not just simple classes.

See also http://docs.jquery.com/Plugins/Validation/validate#toptions for details on other default values that can be set.