Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform validation on hidden fields

I have the view below:

    @Html.LabelFor(m => m.CompanyPostCode)
    @Html.TextBoxFor(m => m.CompanyPostCode)

    @Html.LabelFor(m => m.CompanyCity)
    @Html.TextBoxFor(m => m.CompanyCity)

    @Html.HiddenFor(m => m.CompanyCityID)

All attributes are marked as [Required] in my view model. Then problem is that my CompanyCityID (marked as Required) is hidden and thus no validation is done in the view. If I show this attribute in my view the validation is done.

enter image description here

My question: is it possible to perform a validation on a hidden field? A workaround exist?

It may seems a little strange to validate a hidden field. The reason is that this field is filled from jQuery based on special rules. If it is not filled, I know something is not valid on the view.

Thanks.

like image 972
Bronzato Avatar asked Apr 13 '12 06:04

Bronzato


People also ask

How do you validate an empty field?

Testing for empty fields Apart from seeing if the field's value is equal to the empty String, you can also test for an empty field by examining the length of the field's value. Since an empty field will have the empty String as its value, the length of the field's value will be zero.

How do you use hidden form fields?

Hidden form field is used to store session information of a client. In this method, we create a hidden form which passes the control to the servlet whose path is given in the form action area. Using this, the information of the user is stored and passed to the location where we want to send data.


1 Answers

The possible reason can be that there is ignore: ':hidden' line in jquery.validate.unobtrusive.js file.

After 1.9.0 version it is a default behaviour. You can fix that manually by adding

$.validator.setDefaults({ ignore: [] });

As you can see here

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).

like image 64
Chuck Norris Avatar answered Oct 05 '22 02:10

Chuck Norris