Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 872
shake Avatar asked May 17 '10 22:05

shake


2 Answers

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" }) 
like image 121
Gabe Avatar answered Sep 19 '22 13:09

Gabe


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; } 
like image 41
Simon_Weaver Avatar answered Sep 19 '22 13:09

Simon_Weaver