7

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,
    });
});
Community
  • 1
  • 1
Houman
  • 64,245
  • 87
  • 278
  • 460
  • this post explains issue http://stackoverflow.com/questions/11232310/how-can-i-use-jquery-validation-with-the-chosen-plugin – charlietfl Dec 23 '12 at 20:04
  • also look at this plugin that has validation in it's API: http://ivaynberg.github.com/select2/ – charlietfl Dec 23 '12 at 20:06
  • Thanks Charlie. Regarding first comment, the suggested solution is on submit. I need it instantly though. Let me see that plugin. Maybe that helps... – Houman Dec 23 '12 at 20:21
  • I checked debugger, the problem is that `change` fires before `select` actually updates... even worse... it does not update selected.... – zb' Dec 23 '12 at 20:28
  • @charlietfl the plugin seems neat but where do you see a minimum selection validation there? – Houman Dec 23 '12 at 20:31
  • @eicto looking at the fiddle, do you think you can fork it and show me your idea? I am not sure if I follow you. Thanks – Houman Dec 23 '12 at 20:32

2 Answers2

4

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.

DEMO

zb'
  • 8,071
  • 4
  • 41
  • 68
  • I'm wondering to myself about the differences between `.checkForm()` and [`.valid()`](http://docs.jquery.com/Plugins/Validation/valid). I'm not finding any documentation for `checkForm`. – Sparky Dec 23 '12 at 21:19
  • [valid](https://github.com/jzaefferer/jquery-validation/blob/master/jquery.validate.js#L435), [checkForm](https://github.com/jzaefferer/jquery-validation/blob/master/jquery.validate.js#L355) not sure if it good idea to use checkForm, but it really different method, `valid` not check form data itself, while `checkForm` does – zb' Dec 23 '12 at 21:29
  • I'm not saying one way is better than the other as I've been unfamiliar with `checkForm()`. However, `valid()` returns a boolean true/false regarding whether the form passes validation. How could it do that if it didn't check the form data itself? It also triggers any applicable error messages, almost like a `submit` without submission. – Sparky Dec 23 '12 at 23:26
  • @Sparky [.valid](http://jsfiddle.net/vwHMT/6/) not works in that case, because it not invoke check – zb' Dec 23 '12 at 23:30
  • [.form](http://jsfiddle.net/vwHMT/8/) also works, but it does even more than `.checkForm` so i not sure that it is correct to use it here – zb' Dec 23 '12 at 23:32
  • @Sparky `valid: function() {return this.size() === 0;}, size: function() {return this.errorList.length;},` what trigger you talking about ? it just return current state. – zb' Dec 23 '12 at 23:37
  • Quote eicto: _"what trigger you talking about?"_ ~ [Please see this jsFiddle](http://jsfiddle.net/dLsKQ/). – Sparky Dec 23 '12 at 23:51
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/21614/discussion-between-eicto-and-sparky) – zb' Dec 23 '12 at 23:56
  • I simply wanted to know the differences between the two methods for my own edification. If you don't know how to explain, that's ok, because I don't either. However, I am very familiar with how `.valid()` works... and simply saying that it does _"not check form data"_ [does not seem accurate](http://jsfiddle.net/dLsKQ/). – Sparky Dec 24 '12 at 00:01
  • @Sparky I explained in chat – zb' Dec 24 '12 at 00:09
  • @eicto you got it working indeed. Masterpiece. I was able to create a class based solution from your solution, which I am adding as edit to the question. Thanks a lot. +1 – Houman Dec 24 '12 at 01:17
0

I have written my solution with the help of both @eicto and @kave solutions as follow:

 $.validator.addMethod("multiSelectRequired", function (value, element) {
    return element.length > 0;
});
$("#aspnetForm").find('select.multi_select_mandatory').each(function () {
    $(this).change(function () {
        $(this).valid();
    });

    $(this).rules('add', {
        'multiSelectRequired': true
    });
});

When initializing the plugin I add `ignoe:[] in order to not to ignor hidden input from validation.

I am using special plugin for my bootstrap project called bootstrap-multiselect to render checkboxes select - https://github.com/davidstutz/bootstrap-multiselcet

Samih A
  • 403
  • 1
  • 10
  • 15