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

jquery validate()
jquery validation cdn
jquery validate rules
form validation using jquery w3schools
jquery form validation demo with source code
jquery validate success
jquery validate errorplacement
jquery validate groups

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

Documentation, Example: Use submitHandler to process something and then using the default submit. Note that "form" refers to a DOM element, this way the  Now use jQuery validation plugin to validate forms' data in easier way. first,add jQuery library in your file.

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

.validate(), In this tutorial, we'll look at how client side validation can be done using jQuery. We'll see two ways of doing this. First we'll validate a form's data by writing the  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

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'

jQuery Validation Plugin, In this tutorial, you will learn how to use a jQuery plugin to add form validation to your website. Using a jQuery plugin to validate forms serves a  It hooks up the validation rules and messages with the HTML Form that will be validated using the jQuery Validation Plug-in. At last, it creates a function that starts the validation. The CSS to Highlight the Failed Input Element. If the validation fails a textbox, we need to highlight it.

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

    });
});

Form Validation Using Jquery Examples, You can simply use the jQuery Validate plugin as follows. jQuery: $(document).​ready(function () { $('#myform').validate({ // initialize the plugin  Use jQuery to Validate in Real-time. We can detect that a user has started entering their name into the name input with: $('#contact_name').on('input', function() { }); Since the name field is required, we simply need to check whether a value for the input exists. If it exists, we'll apply the valid class and remove any invalid class.

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

Easy Form Validation With jQuery - Tuts+ Code, Now use jQuery validation plugin to validate forms' data in easier way. first,add jQuery library in your file. <script src="https://cdn.jsdelivr  jquery validate work with the name attribute of the input not the Id, maybe that is your problem Justin – Diego_DX Mar 28 '14 at 19:13. For some reason, even with a broad class based selector, jQuery Validator only ever seems to select the first element of that type.

A simple jQuery form validation script, This article will teach you how to validate fields in an HTML contact form using jQuery and JavaScript. Provides code example to validate email  you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

How to validate a form using jQuery?, Adding validation to your forms with JQuery gives you a lot of flexibility as you can add more rules and conditions to your validation and you can customize the​  Add the reference of jQuery scripts file and validation file as in the following: After adding the reference use the following syntax for validation. Now inside the rules section we need to add the control name with the required rules for validation.

How to Validate Form Fields Using jQuery, Multipart, implemented using the jQuery UI accordion and a custom method to check if an element is on the current page when validated; Integration with masked-input plugin, see Phone and Zip fields; link Using remote validation to help with captchas. Features remote validation for helping the user to fill out captchas. Notable features of the demo:

Comments
  • Check this plugin out. Not really a solution but you might want to give it a try.
  • @elclanrs: Thanks but I'd like to stick with the de facto jQuery validation library for now, especially at this point in the project (trying to wrap up). Maybe in a future project.
  • This post solved my problem: stackoverflow.com/questions/10387553/… Simple and elegant.
  • This was quite sufficient in my case. Thanks.
  • Where did you put this line? It doesn't seem to work for me :/
  • just above the JQuery validate() function.
  • Worked for me! Definitely the simplest solution.
  • Because all my chosen selects have the class .chosen-select I find it better to use $.validator.setDefaults({ ignore: ":hidden:not(.chosen-select)" });. Otherwise this would mean all hidden selects would be validated.
  • It seems that the e.preventDefault() isn't even necessary, just calling $("element").valid(). I used this code and it seems to work perfectly: $('form').on('submit', function() {$('.chzn-done').valid();});. Thanks for the info.
  • .chzn-done is no longer added to "chosen" elements as of Chosen 1.0
  • This answer only works if you don't call .chosen(). There seems to be a bug (feature?) in the chosen library that when you activate a <select>, it hides it - so it no longer interacts with the validation rules.
  • In my case, I've added ul.chosen-choices: .input-validation-error { border-color: red !important; } .input-validation-error, .input-validation-error + div.chosen-container ul.chosen-choices { border-color: red !important; }.
  • hello guys, I have a problem with the focus of jqueryvalidation, doesn't work on the chosen fields, do you know how solve that problem ?
  • Ask a new question with some background and gladly will help
  • Doesn't work for me at all. The .chosen-select + .chosen-container:visible part actually selects the chosen's <div> and not the <select> which must be validated, so I'm unclear about how this is supposed to work.