Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chosen.js and validate jquery

I am using validate.jquery.js : works fine. But when I'm adding chosen.js , validation on the select dropdowns doesn't work anymore.

Here is the JS I'm using http://pastebin.com/S9AaxdEN

And here is my select form :

<select name="category" id="category" placeholder="" class="{validate:{required:true}}">
<option value=""><?php echo lang('category_choice'); ?></option>
<option value="vtt">VTT</option>
<option value="autre">Autre type de v&eacute;lo</option>
</select>

Don't know why chosen.js disable the validation, any idea ?

like image 746
pimarc Avatar asked Apr 30 '12 17:04

pimarc


2 Answers

You can fix this by adding the class "chzn-done" that does not take the property "ignore" to "validate.settings":

var settings = $.data($('#myform')[0], 'validator').settings;
settings.ignore += ':not(.chzn-done)';

example

HTML:

<form method="post" id="form1" action="">
    <fieldset>
        <legend>Login Form</legend>
        <div>
            <label>datos</label>
            <select name="data-select" title="data-select is required" class="chzn-select {required:true}" style="width:150px;">
                <option></option>
                <option value="1">uno</option>
                <option value="2">dos</option>
            </select>
        </div>
        <div>
            <label for="phone">Phone</label>
            <input id="phone" name="phone" class="some styles {required:true,number:true, rangelength:[2,8]}" />
        </div>
        <div>
            <label for="email">Email</label>
            <input id="email" name="email" class="{required:true,email:true}">
        </div>

        <div class="error"></div>
        <div>
            <input type="submit" value="enviar datos"/>
        </div>
    </fieldset>
</form>

JS:

$(function() {

    var $form = $("#form1");

    $(".chzn-select").chosen({no_results_text: "No results matched"});
    $form.validate({
        errorLabelContainer: $("#form1 div.error"),
        wrapper: 'div',
    });

    var settings = $.data($form[0], 'validator').settings;
    settings.ignore += ':not(.chzn-done)';

    $('form').each(function(i, el){

        var settings = $.data(this, 'validator').settings;
        settings.ignore += ':not(.chzn-done)';

    });

});
like image 124
andres descalzo Avatar answered Sep 21 '22 18:09

andres descalzo


I would just add that for the error placement, it will append the element right next to hidden, therefore you may want to change the placement by using the following code on your validate function as an option argument

errorPlacement: function(error,element) {
        if (element.is(":hidden")) {
            //console.log(element.next().parent());
            element.next().parent().append(error);
        }
        else {
            error.insertAfter(element);
        }

    }
like image 22
momo Avatar answered Sep 19 '22 18:09

momo