w00
w00

Reputation: 26782

Disable validation for an element with jQuery Unobtrusive Validation

I am generating a list of elements on a page, and they all have validators attached to them. When I look in the HTML source, I see something like:

<input type="text" id="email" name="email" data-val-required="No valid email address!" data-val="true">

I need a way to dynamically enable/disable the validation for such an element. I tried to enable/disable the data-val attribute by setting it to false and then back to true. But it doesn't seem to response to that; the validation is always there!

Does anyone have any idea how I can enable/disable validators on certain fields dynamically?

Upvotes: 13

Views: 23594

Answers (4)

David Bouška
David Bouška

Reputation: 133

I would add one more option without overriding unobtrusive validator defaults. As validation for specific element is controled by data-val attribute, you can set it as data-val="false".

So for Razor helper, use:

@Html.TextBoxFor(model => Model.DateOfBirth, new { @class = "form-control", data_val = false })

and for new .net core syntax, use:

<input asp-for="DateOfBirth" class="form-control" data-val="false">

Upvotes: 2

endyourif
endyourif

Reputation: 2202

This worked better for me:

$('#Reference').rules('add', 'required');
$('#Reference').rules('add', 'remove');
$('#Reference').rules('add', { minlength: 2 });

Upvotes: 1

Santiago Rebella
Santiago Rebella

Reputation: 168

I think this will help.

<div class="editor-field">
       @{ Html.EnableClientValidation(false); }
       @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" })
       @{ Html.EnableClientValidation(true); }
</div>

Upvotes: 15

w00
w00

Reputation: 26782

I actually found a solution that fits my needs better. I can do the following:

$(function() {
    var settngs = $.data($('form')[0], 'validator').settings;
    settngs.ignore = ".ignore";
});

And with that i can 'toggle' any element that i want by adding or removing the classname ignore from an element.

Upvotes: 51

Related Questions