【发布时间】:2013-12-13 11:22:46
【问题描述】:
如何正确验证使用 Select2 的选项值?在更改为任何其他值之前设置了某个值时,我遇到了问题。它看起来正确,但在我更改值之前会显示验证错误。感谢您的帮助。
【问题讨论】:
-
你能用一些代码证明这个问题吗?我无法想象你的意思。
标签: jquery-select2 jquery-validation-engine
如何正确验证使用 Select2 的选项值?在更改为任何其他值之前设置了某个值时,我遇到了问题。它看起来正确,但在我更改值之前会显示验证错误。感谢您的帮助。
【问题讨论】:
标签: jquery-select2 jquery-validation-engine
【讨论】:
在 select2.js 文件中
找到这个(第 341 行)
if (this.indexOf("select2-") !== 0) {
并替换为
if (this.indexOf("select2-") !== 0 && this !== "validate[required]") {
【讨论】:
我遇到了同样的问题。所以在select2.min.js中找到这个笔画(脚本中应该是2个笔画):
D(this.container,this.opts.element,this.opts.adaptContainerCssClass)
并在您找到的笔划后立即添加此代码
,this.container.removeClass("validate[required]")
这应该可以解决您的问题。
【讨论】:
将此 CSS 添加到您的 head 标签中。
.has-error {
border-color: #dd4b39 !important;
}
这就是我为 Jquery 验证引擎调用 select2 的方式。
$("#form").validate( {
ignore: ".ignore, .select2-input",
rules: {
txtproduct: "required",
txtwarehouse: "required",
//txtdescription: "required",
txtquantity: {required:true,number:true},
txtrate: {required:true,number:true},
txtdiscounttype: "required",
txtdiscount: {required:true,number:true},
txtamount: {required:true,number:true},
},
highlight: function ( element, errorClass, validClass ) {
$(element).addClass("has-error");
if($(element).hasClass('select2-hidden-accessible'))
{
$(element).next().find("[role=combobox]").addClass('has-error');
}
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass("has-error");
if($(element).hasClass('select2-hidden-accessible'))
{
$(element).next().find("[role=combobox]").removeClass('has-error');
}
}
} );
}
【讨论】:
Select2 库将原来的选择器隐藏起来,验证引擎对隐藏的元素不起作用,所以先让可见,然后验证引擎才能看到。第二个是我们需要为我们隐藏选择器元素,大约有两种方法可以做到,例如将其不透明度设置为“0”,或者将其高度/宽度设置为“0px”,实际上我们都需要。
下面是代码示例:
$("select").select2();
$.each($(".select2-container"), function (i, n) {
$(n).next().show().fadeTo(0, 0).height("0px").css("left", "auto"); // make the original select visible for validation engine and hidden for us
$(n).prepend($(n).next());
$(n).delay(500).queue(function () {
$(this).removeClass("validate[required]"); //remove the class name from select2 container(div), so that validation engine dose not validate it
$(this).dequeue();
});
});
参考:http://wangweiqiang.net/how-to-make-jquery-validation-engine-works-well-for-select2/
【讨论】: