I\'m using MVC3 with unobtrusive validation. I have a field that the user is expected to fill with some data and then press a \"search\" button. If search has never been pressed
try
var validator = $("#myFormId").data('validator');
validator.settings.ignore = "";
Here is an informative blog post
EDIT
@RAM suggested a better solution please FOLLOW
In some cases you want just ignore validation on one or several
hidden fields (not all hidden field) in client side
and also you want validate them and other hidden fields in server side
.
In these cases you have validation attributes for all hidden fields in your ViewModel
and they will be used to validate the form when you post it (server side
).
Now you need a trick to just validate some of the hidden fields in client side (not all of them). In these cases i recommend you to use my mechanism!
Set data-force-val
as true
in the target hidden input tags. It's our custom attribute that we use to detect target hidden inputs witch we want validate them in client side.
// This hidden input will validate both server side & client side
<input type="hidden" value="" name="Id" id="Id"
data-val-required="The Id field is required."
data-val="true"
data-force-val="true">
// This hidden input will validate both server side & client side
<input type="hidden" value="" name="Email" id="Email"
data-val-required="The Email field is required."
data-val="true"
data-force-val="true">
// This hidden input just will validate server side
<input type="hidden" value="" name="Name" id="Name"
data-val-required="The Neme field is required."
data-val="true">
Also you can set data_force-val
for your hidden inputs by jQuery
:
$("#Id").attr("data-force-val", true); // We want validate Id in client side
$("#Email").attr("data-force-val", true); // We want validate Email in client side
$("#Name").attr("data-force-val", false); // We wont validate Name in client side (This line is not necessary, event we can remove it)
Now, active data-force-val="true"
functionality by some simple codes like these:
var validator = $("#TheFormId").data('validator');
validator.settings.ignore = ":hidden:not([data-force-val='true'])";
Note: validator.settings.ignore
default value is :hidden
I had a similar problem, and I used this code to change defaults, in MVC 4:
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$.validator.setDefaults({
ignore: ""
})
</script>
Source: JQuery validate