Selectize.js and jQuery validation
Asked Answered
Y

3

11

I'm trying to validate a form that uses the Selectize.js to select and jQuery Validation plugin for validation.

I can not make it work. The script validates the input fields, but not the select:

<form id="test" method="post" action="#">
Name: <input name="name" type="text">

<select name="person" id="select-beast" class="demo-default" placeholder="Select">
    <option value="">Select...</option>
    <option value="1">First</option>
    <option value="2">Second</option>n>
</select>

    <button type="submit" class="btn btn-primary col-md-12 col-lg-12">Go</button>
</form>

JS:

$('#select-beast').selectize({
    create: true,
    sortField: 'text'
});
    

// validate signup form on keyup and submit
$("#test").validate({
    errorElement: 'label',
    errorClass: 'error',
    rules: {
        name: {
            required: true
        },
        person: {
            required: true
        }
    },
    messages: {
        name: "Insert name.",
        person: "Insert person.",
    }
});

http://jsfiddle.net/8nVqS/

Yanez answered 27/3, 2014 at 19:24 Comment(0)
T
20

The reason is that jQuery.validation plugin will ignore all hidden element when validating by default.

And Selectize.js will hide the given jQuery object, So your name field will run validate but person field will not.

Solution, please reference this gist: How to validate selectize.js comboboxes with the jQuery validation plugin

Tightfisted answered 3/5, 2014 at 14:39 Comment(1)
Thanks for the help, Need some more supportConure
S
8

The answers provided above aren't working with selectize.js v0.12.3 or greater.

That is happening due to the fact that the required attribute is removed from the select in refreshValidityState function - see https://github.com/selectize/selectize.js/commit/abc8a560a8335a017790c2a799925cc123670bfc

A quick fix for this is to add the selects that are required in the rules array of the validation options object.

Example:

var validator = $("#form").validate({
            ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input',
            rules: {
                "select-name-here": "required",
                "select-name-here2": "required"
            }
        });
Slur answered 14/11, 2016 at 16:20 Comment(0)
W
3

I am using

ignore: ':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input',

and it works for me.

Woke answered 11/2, 2016 at 6:13 Comment(2)
Where does that go?Speak
$("#test").validate({ ignore:IT_WILL_BE_HERE });Woke

© 2022 - 2024 — McMap. All rights reserved.