I have some <select>
inputs using the chosen plugin that I want to validate as "required" on the client side. Since "chosen" hides the actual select element and creates a widget with divs and spans, native HTML5 validation doesn't seem to work properly. The form won't submit (which is good), but the error message is not shown, so the user has no idea what's wrong (which is not good).
I've turned to the jQuery validation plugin (which I planned on using eventually anyways) but haven't had any luck so far. Here's my test case:
<form>
<label>Name: <input name="test1" required></label>
<label>Favorite Color:
<select name="test2" required>
<option value=""></option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
</label>
<input type="submit">
</form>
$(document).ready(function(){
$('select').chosen();
$('form').validate();
});
This is letting the select
through with an empty value, without validating or showing the error message. When I comment out the chosen()
line, it works fine.
How can I validate chosen()
inputs with the jQuery validation plugin, and show the error message for invalid ones?
jQuery validate ignores the hidden element, and since the Chosen plugin adds visibility:hidden
attribute to the select, try:
$.validator.setDefaults({ ignore: ":hidden:not(select)" }) //for all select
OR
$.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" }) //for all select having class .chosen-select
Add this line just before validate()
function. It works fine for me.