I am able to validate a multi-select with jquery-validate and have created a fiddle as demo. Unselect the selection by holding Ctrl and click on the selection to see the effect.
<form id="myform">
<select id="id_deals-1-sales_item" class="multi_select_mandatory" name="deals-1-sales_item" multiple="multiple">
<option value="1">Hotel 3 Star</option>
<option selected="selected" value="2">Hotel 4 Star</option>
</select>
</form>
$(document).ready(function() {
var validator = $('#myform').validate({
// options
rules: {
"deals-1-sales_item": "required",
},
//ignore: ':hidden:not("#id_deals-1-sales_item")'
});
});
But as soon as I chosenify the multi select it stops working: See fiddle.
$('#id_deals-1-sales_item').chosen();
While researching I found that someone has tried this with jquery multiselect
instead of chosen. It seems hidden elements are ignored in jquery validate. I tried to apply that solution but since Chosen has different methods, I got stuck (multiselect doesn't exist in chosen)
Is here any jQuery guru that could point me to the right direction? Besides I would rather have the solution based on classes rather than based on field names. Like this:
This is a solution I came up with half way through. But don't know how to proceed with ???
.
$.validator.addMethod("needsSelection", function(value, element) {
return $(element).???.length > 0;
});
var validator = $('#myform').validate({
});
$('#myform').find('select.multi_select_mandatory').each(function(){
$(this).change(function(){
$(this).valid();
});
$(this).rules('add', {
needsSelection: ""
});
});
Solution:
With eicto's solution below, I was able to create a class based instead of field name based solution. This is specially useful when you have dynamic elements that you want to validate instantly without submitting anything to the server.
var validator = $('#deal_modal_form').validate({
// options
ignore: ':hidden:not(.chzn-done)'
});
$('#myform').find('select.multi_select_mandatory').each(function(){
$(this).chosen().change(function(){
$(this).valid();
});
$(this).rules('add', {
required: true,
});
});
This works for me:
$(document).ready(function() {
var validator = $('#myform').validate({
// options
rules: {
"deals-1-sales_item": "required",
},
ignore: ':hidden:not(.chzn-done)'
});
var checkerrors = function() {
validator.form();
};
var chosen = $('#id_deals-1-sales_item').chosen().change(checkerrors);
});
the idea is to check form manually on each change.