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?
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" })
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With