How can I use jQuery validation with the “chosen” plugin?

荒凉一梦 提交于 2019-11-26 08:05:22

问题


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?


回答1:


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.




回答2:


jQuery validation isn't going to pick up elements that are hidden, but you can force it to validate individual elements. Bit of a hack, but the following will work:

$('form').on('submit', function(e) {
    if(!$('[name="test2"]').valid()) {
        e.preventDefault();
    }
});  

To select only "chosen" elements you can use $('.chzn-done')




回答3:


in mine.

my form has class 'validate' and every input element has class 'required' html code:

<form id="ProdukProdukTambahForm" class="validate form-horizontal" accept-charset="utf-8" method="post" enctype="multipart/form-data" action="/produk-review/produk/produkTambah" novalidate="novalidate">
     <div class="control-group">
        <label class="control-label" for="sku">SKU</label>
        <div class="controls">
           <input id="sku" class="required span6" type="text" name="sku">
        </div>
     </div>
     <div class="control-group">
        <label for="supplier" class="control-label">Supplier</label>
        <div class="controls">
            <select name="supplier" id="supplier" class='cho span6 {required:true} '>                                           
                <option value=''>-- PILIH --</option>
                <?php
                foreach ($result as $res)
                    {
                    echo '<option value="'.$res['tbl_suppliers']['kode_supplier'].'">'.$res['tbl_suppliers']['nama_supplier'].'</option>';
                    }
                ?>
            </select>
         </div>
      </div>
</form>

and javascript code for choosen with jquery validation

$(document).ready(function() {
    // - validation
    if($('.validate').length > 0){
        $('.validate').validate({
            errorPlacement:function(error, element){
                    element.parents('.controls').append(error);
            },
            highlight: function(label) {
                $(label).closest('.control-group').removeClass('error success').addClass('error');
            },
            success: function(label) {
                label.addClass('valid').closest('.control-group').removeClass('error success').addClass('success');
            },
            //validate choosen select (select with search)
            ignore: ":hidden:not(select)"
        });
    }
    // - chosen, add the text if no result matched
    if($('.cho').length > 0){
        $(".cho").chosen({no_results_text: "No results matched"});
    }
});

note: if the input value is null, the class error will be append to parent 'div'




回答4:


//You can fix this by using another way to hide your chosen element. eg....

$(document).ready(function() {
 $.validator.addMethod(     //adding a method to validate select box//
            "chosen",
            function(value, element) {
                return (value == null ? false : (value.length == 0 ? false : true))
            },
            "please select an option"//custom message
            );

    $("form").validate({
        rules: {
            test2: {
                chosen: true
            }
        }
    });
    $("[name='test2']").css("position", "absolute").css("z-index",   "-9999").chosen().show();

    //validation.....
    $("form").submit(function()
    {
        if ($(this).valid())
        {alert("valid");
    //some code here 
        }
        return false;

    });
});



回答5:


this simple CSS rule works on joomla 3's implementation of chosen

Chosen adds the class invalid to the hidden select input so use this to target the chosen select box

.invalid, .invalid + div.chzn-container a {
    border-color: red !important;
}



回答6:


You might also running into trouble that error message is displayed before Chosen dropdownlist. I found out the solution to resolve this issue and paste my code here to share with you

HTML:

<label class="col-sm-3">Select sponsor level *</label>
<asp:DropDownList ID="ddlSponsorLevel" runat="server" CssClass="col-sm-4 required" ClientIDmode="Static" />
<label class="error" id="ddlSponsorLevel-error" for="ddlSponsorLevel"></label>

Javascript:

if (!$('#ddlSponsorLevel').valid()) {
       $('#ddlSponsorLevel-error').text("You must choose a sponsor level");
            return false;
}

Jquery Validation actually added a hidden label html element. We can re-define this element with same ID on different place to overwrite original place.




回答7:


I spent about a day working on this and had no luck at all! Then I looked at the source code Vtiger was using and found gold! Even though they were using older versions they had the key! you have to use

data-validation-engine="validate[required]"

If you don't and you have it where classes are passed through the class for the select gets applied to the chosen and it thinks that your chosen never gets updated. If you don't pass the class onto the chosen this should be a problem, BUT if you do this is the only way it will work.

This is with chosen 1.4.2 validationEngine 2.6.2 and jquery 2.1.4

// binds form submission and fields to the validation engine
jQuery("#FORMNAME").validationEngine({
    prettySelect : true,
    useSuffix: "_chosen"
    //promptPosition : "bottomLeft"
});



回答8:


I had to place $.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
outside $(document).ready(function() in order to work with chosen.js.

https://stackoverflow.com/a/10063394/4063622




回答9:


@Anupal put me on the right path but somehow I needed a complex fix

Enable .chosen to be considered

javascript

$.validator.setDefaults({ ignore: ":hidden:not(.chosen)" })

Or any other name you give to your chosen's. This is global configuration. Consider setting on top level

Create custom rule for chosen

Thanks to BenG

html

<select id="field" name="field" class="chosen" data-rule-chosen-required="true">
    <option value="">Please select…</option>
</select>

javascript

Again, global configuration for $.validator object. Can be put next to the previous command

$.validator.addMethod('chosen-required', function (value, element, requiredValue) {
    return requiredValue == false || element.value != '';
}, $.validator.messages.required);



回答10:


jQuery("#formID").validationEngine({
     prettySelect : true,
     useSuffix: "_chzn"
});

jQuery-Validation-Engine/demoChosenLibrary




回答11:


You can also try this:

$('form').on('submit', function(event) {
    event.preventDefault();
    if($('form').valid() == true && $('.select-chosen').valid() == true){
        console.log("Valid form");
    } else {
        console.log("Invalid form");
    }
}); 

Remember to add .select-chosen class on each selects.

$('.select-chosen').valid() forces the validation for the hidden selects

http://jsfiddle.net/mrZF5/39/




回答12:


My form includes conditionally hidden fields, to prevent the hidden chosen fields failing validation I've extended the default ignore:hidden a little further:

$.validator.setDefaults({ 
  ignore: ":hidden:not(.chosen-select + .chosen-container:visible)"  //for all select having class .chosen-select
    })



回答13:


I think this is the better solution.

//trigger validation onchange
$('select').on('change', function() {
    $(this).valid();
});

$('form').validate({
    ignore: ':hidden', //still ignore Chosen selects
    submitHandler: function(form) { //all the fields except Chosen selects have already passed validation, so we manually validate the Chosen selects here            
        var $selects = $(form).find('select'),
            valid = true;
        if ($selects.length) {
            //validate selects
            $selects.each(function() {
                if (!$(this).valid()) {
                    valid = false;
                }
            });
        }
        //only submit the form if all fields have passed validation
        if (valid) {
            form.submit();
        }
    },
    invalidHandler: function(event, validator) { //one or more fields have failed validation, but the Chosen selects have not been validated yet
        var $selects = $(this).find('select');     
        if ($selects.length) {
            validator.showErrors(); //when manually validating elements, all the errors in the non-select fields disappear for some reason

            //validate selects
            $selects.each(function(index){
                validator.element(this);
            })
         }
    },
    //other options...
});

Note: You will also need to change the errorPlacement callback to handle displaying the error. If your error message is next to the field, you will need to use .siblings('.errorMessageClassHere') (or other ways depending on the DOM) instead of .next('.errorMessageClassHere').




回答14:


In the year 2018 I am verifying that jQuery validate is complaining about an input field with no name. This input field is appended by the jQuery Chosen plguin.

This bug is happening before anything else when using chosen.




回答15:


Thanks this answer https://stackoverflow.com/a/40310699/4700162 i resolve the iussue:

Inside the file the Chosen.jquery.js, change

this.form_field_jq.hide().after(this.container);

with this:

this.form_field_jq.css('position', 'absolute').css('opacity', 0).after(this.container);



回答16:


you can use jQuery validation for “chosen” plugin. Working fine for me.

$('.chosen').chosen({
        allow_single_deselect: true
    });
    $.validator.setDefaults({ ignore: ":hidden:not(select)" });
        $('form').validate({
            highlight: function(element) {
                $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorElement: 'span',
        errorClass: 'help-block text-danger',
        errorPlacement: function(error, element) {
            if(element.parent('.input-group').length) {
                error.insertAfter(element.parent());
            } else {
                error.insertAfter(element.parent());
            }
        }
    });


来源:https://stackoverflow.com/questions/11232310/how-can-i-use-jquery-validation-with-the-chosen-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!