参考文献

How can I use jQuery validation with the “chosen” plugin?

环境说明

  • jQuery v2.2.4
  • chosen 1.8.7
  • jQuery Steps v1.0.6

步骤说明

如封面图,我的品牌与最后级分类使用的是chosen控件,套在了jQuery Steps中,验证时会忽略chosen控件

解决方法

参考文献中已经说明原因

jQuery validate 会忽略隐藏元素,因为Chosen插件为Select添加了visibility:hidden属性

$.validator.setDefaults({ignore: ":hidden:not(select)"}) // for all select
OR
$.validator.setDefaults({ignore: ":hidden:not(.chosen-select)"}) // for all select having class .chosen-select

简单的示例代码

<!-- form start -->
<form id="axinblogForm" class="form-horizontal wizard-big">
    <h1>基本信息</h1>
    <fieldset>
        <div class="form-group">
            <label class="col-sm-2 control-label">品牌:</label>
            <div class="col-sm-9">
                <select lay-ignore id="brand_id" name="brand_id" class="form-control chosen"
                        data-placeholder='请选择品牌'>
                    <option value="">请选择</option>
                    {sql query="select brand_id,name,pid from axin_brand "}
                        <option value="{$sql.brand_id}" {if condition="$info.pid eq $sql.brand_id"}selected{/if}>
                            {$sql.name}
                        </option>
                    {/sql}
                </select>
            </div>
        </div>
    </fieldset>
</form>
$("#axinblogForm").steps({
    bodyTag: "fieldset",
    onStepChanging: function (event, currentIndex, newIndex) {
        return form.valid();
    },
    onStepChanged: function (event, currentIndex, priorIndex) {
    },
    onFinishing: function (event, currentIndex) {
        return form.valid();
    },
    onFinished: function (event, currentIndex) {
    },
    onCanceled: function (event) {
    },
}).validate({
    ignore: ":hidden:not(select)",
    // or ignore: ":hidden:not(.chosen)",
    transitionEffect: "slideLeft",
    errorPlacement: function (error, element) {
        element.before(error);
    },
    rules: {
        brand_id: {
            required: true
        },
    },
    messages: {
        brand_id: {
            required: "产品品牌必选"
        },
    },
});

别忘记选中后需要消除错误

$(".chosen").change(function () {
    $(this).valid();
})