jquery.validate v. 1.9 ignores some hidden inputs

2019-02-15 19:12发布

问题:

with version 1.7 everything works ok, all hidden inputs get validated,
but with version 1.9 some do and some don't
I use asp.net mvc 3 and jquery.validate + jquery.unobtrusive (jquery 1.7.1)

this is the generated html:

    <!--this gets validated-->
        <input type="hidden" data-val="true" data-val-number="The field Chef must be a number." data-val-required="The Chef field is required." value="" name="Chef" id="Chef">    
<span data-valmsg-replace="true" data-valmsg-for="Chef" class="field-validation-valid"></span>

    <!--this one is ignored-->
        <input type="hidden" data-val="true" data-val-number="The field MyFruit must be a number." data-val-required="The MyFruit field is required." value="" name="MyFruit" id="MyFruit">
<span data-valmsg-replace="true" data-valmsg-for="MyFruit" class="field-validation-valid"></span>

anybody knows why could this happen ?

回答1:

With 1.9 version validation plugin ignores :hidden elements by default.

Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes).

Because you're using unobtrusive version, you can't set any option. So you don't init plugin yourself, therefor you have to change it's setting after it's initialized. You can fix it like this:

var validatorSettings = $.data($('form')[0], 'validator').settings;
validatorSettings.ignore = "";

This code works for first form element in the markup, you can specify your form(s) and change default behaviour.