selectize.js和jquery验证

Iva*_*van 8 javascript validation jquery selectize.js

我正在尝试验证使用selectize.js选择和jqueryvalidation.org进行验证的表单.

我不能让它发挥作用.该脚本验证输入字段,但不验证选择:

<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>
Run Code Online (Sandbox Code Playgroud)

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.",
    }
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/8nVqS/

小智 16

原因是jQuery.validation插件在默认情况下进行验证时会忽略所有隐藏元素.

并且Selectize.js将隐藏给定的jQuery对象,因此您的名称字段将运行validate但person字段将不会.

解决方案,请参考这个要点:如何使用jQuery验证插件验证selectize.js组合框


Cri*_*ara 6

上面提供的答案不适用于selectize.js v0.12.3或更高版本.

这是因为在refreshValidityState函数中从select中删除了必需属性- 请参阅https://github.com/selectize/selectize.js/commit/abc8a560a8335a017790c2a799925cc123670bfc

快速定为这是添加在本选择所需的验证选项对象的规则阵列英寸

例:

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"
            }
        });
Run Code Online (Sandbox Code Playgroud)