How can I use jQuery validation with the "chosen" plugin?

JqueryJquery ValidateJquery Chosen

Jquery Problem Overview


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 Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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')

Solution 3 - Jquery

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'

Solution 4 - Jquery

//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;

    });
});

Solution 5 - Jquery

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;
}

Solution 6 - Jquery

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

Solution 7 - Jquery

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.

Solution 8 - Jquery

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"
});

Solution 9 - Jquery

@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);

Solution 10 - Jquery

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').

Solution 11 - Jquery

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

jQuery-Validation-Engine/demoChosenLibrary

Solution 12 - Jquery

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/

Solution 13 - Jquery

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
    })

Solution 14 - Jquery

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.

enter image description here

This bug is happening before anything else when using chosen.

Solution 15 - Jquery

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);

Solution 16 - Jquery

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());
            }
        }
    });

Solution 17 - Jquery

After calling chosen() use below jquery method

$("#id").css("display":"").addClass("sr-only");

sr-only is boot strap class

Solution 18 - Jquery

I ended up solving it by doing the following:

This was for Chosen v1.8.7:

  1. Open chosen.js and on line 199 locate this:

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

  1. Replace that with this:

this.form_field_jq.addClass('chosen-master').after(this.container),

  1. Add these CSS attributes to that class:
.chosen-master {
  display: inline-block !important;
  width: 1px;
  height: 1px;
  margin: 0;
  padding: 0;
  border: 0;
}

Reference: https://stackoverflow.com/a/64491538/7353382

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWesley MurchView Question on Stackoverflow
Solution 1 - JqueryAnupalView Answer on Stackoverflow
Solution 2 - JqueryMike RobinsonView Answer on Stackoverflow
Solution 3 - JqueryAcang TerpalView Answer on Stackoverflow
Solution 4 - Jqueryvikrant singhView Answer on Stackoverflow
Solution 5 - JqueryphilipView Answer on Stackoverflow
Solution 6 - JqueryTobi G.View Answer on Stackoverflow
Solution 7 - JqueryGavin TianView Answer on Stackoverflow
Solution 8 - JqueryMav2287View Answer on Stackoverflow
Solution 9 - JqueryAlwin KeslerView Answer on Stackoverflow
Solution 10 - JquerynoypiscripterView Answer on Stackoverflow
Solution 11 - JquerydsmoreiraView Answer on Stackoverflow
Solution 12 - JqueryFred KView Answer on Stackoverflow
Solution 13 - JqueryecolemaView Answer on Stackoverflow
Solution 14 - JqueryMarkSkayffView Answer on Stackoverflow
Solution 15 - JqueryAntonio FaienzaView Answer on Stackoverflow
Solution 16 - JqueryAltafView Answer on Stackoverflow
Solution 17 - JqueryMahammad MoineView Answer on Stackoverflow
Solution 18 - JqueryDani AmsalemView Answer on Stackoverflow