user2897975 user2897975 - 6 months ago 100
Javascript Question

Client Side validation for a particular hidden field in

I am using data annotation for validation and also using unobtrusive.js for client side validation.
I have several hidden fields that are not validated (and I don't need) by default as per the default setting of jquery.validate.js (ignore: ":hidden").
In my case I just want to validate a particular hidden field and not the all as a result I can't override
ignore: ":hidden" to ignore:[].
If it is changed then all hidden fields will be considered for validation which is not my requirement.

Have no idea how to enable validation for a particular hidden field.

[ValidDate(ErrorMessage = "This is not a valid date.Please enter date in dd/mm/yyyy format.")]
public string HiddenSelectedDob { get; set; }

Where ValidDate is a custom attribute.

Here I am taking input from the user for the day , month and year from three different dropdowns and for the change event of each drop down the value of the HiddenSelectedDob will be set using jquery.
Finally on submit this hidden filed should be validate.

I have given a class name to that hidden filed like..

@Html.HiddenFor(m => m.HiddenSelectedDob, new { @class = "validateAlways" })

and override the default setting of jqury.validate.js like

$.validator.setDefaults({ ignore: ":hidden:not(.validateAlways)" });

but the result is same. The filed is not validating.


Well, the only way I see is to add a class to the hidden input that you wanna validate.

So you'll have to do this at the view level.

@Html.HiddenFor(x => x.HiddenSelectedDob, new{@class="validateAlways"})

Then, change the ignore rule of validate.js to

ignore: ':hidden:not('.validateAlways')'

Which means : ignore all hidden inputs, except if they have a validateAlways class.