How can I use jQuery validation with the "selected" plugin?
I have several <select> inputs using the selected plugin , which I want to check as "required" on the client side. Since the "selected" hides the actual select element and creates the widget with divs and spans, the HTML5 built-in check does not seem to work properly. The form will not be submitted (which is good), but the error message is not displayed, so the user does not know what is wrong (which is not good).
I turned to the jQuery validation plugin (which I planned to use anyway), but so far no luck. Here is 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 passes select through an empty value without checking or displaying an error message. When I comment on the chosen() , it works fine.
How can I check chosen() inputs with jQuery validation plugin and show error message for invalid?
jQuery validate ignores the hidden element, and since the Chosen plugin adds the visibility:hidden attribute to the selection, 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 immediately before the validate() function. This works great for me.

Validation jQuery does not collect elements that are hidden, but you can force it to validate individual elements. A bit of a hack, but the following will work:
$('form').on('submit', function(e) { if(!$('[name="test2"]').valid()) { e.preventDefault(); } }); To select only the βselectedβ items, you can use $('.chzn-done')
in my.
my form has a class 'validate' and each input element has a 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 to select 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, a class error will be added to the parent "div"
// You can fix this using another way to hide the item you selected. 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; }); }); You may have encountered a problem that an error message is displayed in front of the dropdown list of favorites. I found a solution to solve this problem 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 html tag element. We can override this element with the same identifier in another place to overwrite the original place.
this simple CSS rule works on the implementation of joomla 3 selected
The selected one adds the class to the hidden selection input, so use it to target the selected selection box
.invalid, .invalid + div.chzn-container a { border-color: red !important; } @Anupal set me on the right track, but somehow I needed a complicated fix
Include .chosen for review
Javascript
$.validator.setDefaults({ ignore: ":hidden:not(.chosen)" }) Or any other name you give to your favorites. This is a global configuration. Consider the top-level setup
Create your own rule for the selected
Thanks BenG
HTML
<select id="field" name="field" class="chosen" data-rule-chosen-required="true"> <option value="">Please selectβ¦</option> </select> Javascript
Again, the global configuration for the $.validator . You can put next to the previous command
$.validator.addMethod('chosen-required', function (value, element, requiredValue) { return requiredValue == false || element.value != ''; }, $.validator.messages.required); I think this is the best 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 modify the errorPlacement to handle the error message. If your error message is next to the field, you need to use .siblings('.errorMessageClassHere') (or other methods depending on the DOM) instead of .next('.errorMessageClassHere') .
jQuery("#formID").validationEngine({ prettySelect : true, useSuffix: "_chzn" }); You can also try the following:
$('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 the .select-chosen class for each select s.
$('.select-chosen').valid() forcibly checks for hidden select s
I spent about a day working on it, and I was out of luck! Then I looked at the source code that Vtiger used and found gold! Despite using older versions, they had a key! you should use
data-validation-engine="validate[required]" If you do not, and you have it, where the classes go through the class so that the selection is applied to the selected one and it considers that your selected one is never updated. If you do not pass the class on the selected one, this will be a problem, but if you do this, this will be the only way this will work.
This is with selected 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" }); My form includes conditionally hidden fields to prevent hidden selected fields with validation errors. I expanded the default ignore: hid a bit more:
I had to post $.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" })
outside of $(document).ready(function() to work with selected.js.
stack overflow