Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making unobtrusive validation work when using Select2 ASP.NET MVC

Select boxes converted to Select2, do not automatically integrate with unobtrusive validation mechanism in ASP.NET MVC framework.
For example, on a form which contains a regular select box (marked as required in model definition), submitting the form while no options have been selected in the select box, will cause the border and background of the select box to take a reddish color, and by using @Html.ValidationMessageFor, error messages, if any, can be displayed beside the box. However if the select box is converted to a Select2 component, then none of the mentioned features work any more. Even the validation error message will not show up.
It seems that the reason for even the validation error message not showing, is because Select2 changes the display CSS property of the original select box to none (display:none), and I guess the unobtrusive validation script does not bother generating error messages for invisible fields.

Any ideas / solutions?

like image 325
Majix Avatar asked Dec 21 '12 20:12

Majix


1 Answers

This issue isn't really specific to Select2, but rather to the jQuery unobtrusive validator.

You can turn on validation for hidden fields as highlighted in this answer.

$.validator.setDefaults({
    ignore: ''
});

As the comments noted, it didn't work inside an anonymous callback function within $(document).ready(). I had to put it at the top level.

like image 69
Jujuba Avatar answered Oct 25 '22 20:10

Jujuba