如何使 select2 与 jquery.validation 插件一起工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23825135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make select2 work with jquery.validation plugin?
提问by user2323711
I'm trying to validate select2 field using jquey.validation plugin but nothing happens.
我正在尝试使用 jquey.validation 插件验证 select2 字段,但没有任何反应。
I want to make select required field.
我想选择必填字段。
I'm using this custom validation function:
我正在使用这个自定义验证功能:
$.validator.addMethod("requiredcountry", function(value, element, arg){
return arg != value;
}, "Value must not equal arg.");
and this is the rule:
这是规则:
rules:
{
country:
{
required: true,
requiredcountry: ""
}
}
What select2 field should I use for the rule to match?
我应该使用哪个 select2 字段来匹配规则?
I appreciate any idea how to make select2 working together with jquery.validation
我很欣赏如何让 select2 与 jquery.validation 一起工作的任何想法
10x
10倍
回答by ABIRAMAN
Just add ignore: [],
in Your form validation function. It will enable hidden field validation.So You will get validation for Select 2
只需添加ignore: [],
您的表单验证功能。它将启用隐藏字段验证。因此您将获得 Select 2 的验证
$("#ContactForm").validate({
ignore: [],
rules: {
//Rules
},
messages: {
//messages
}
});
回答by Chad Kuehn
I have detailed this in a blog post: http://chadkuehn.com/jquery-validate-select2/
我在博客文章中对此进行了详细说明:http: //chadkuehn.com/jquery-validate-select2/
When you place a Select2 on a SELECT tag it hides the original element. So in the validation plugin you must adjust the proper wrapping markup when highlighting and unhighlighting.
当您将 Select2 放在 SELECT 标签上时,它会隐藏原始元素。因此,在验证插件中,您必须在突出显示和取消突出显示时调整正确的包装标记。
highlight: function (element, errorClass, validClass) {
var elem = $(element);
if (elem.hasClass("select2-offscreen")) {
$("#s2id_" + elem.attr("id") + " ul").addClass(errorClass);
} else {
elem.addClass(errorClass);
}
},
unhighlight: function (element, errorClass, validClass) {
var elem = $(element);
if (elem.hasClass("select2-offscreen")) {
$("#s2id_" + elem.attr("id") + " ul").removeClass(errorClass);
} else {
elem.removeClass(errorClass);
}
}
View a DEMOhere.
在此处查看演示。
回答by Alireza Fattahi
As a tip, please consider that the validate js bind itself to changes of select not select 2. This cause problem in below case:
作为提示,请考虑验证 js 将自身绑定到 select not select 2 的更改。这会导致以下情况出现问题:
- There is a required
select box
which and is converted toselect2
- You click the submit and the error shows that the select box is required.
- You select some option from select 2.
- The validation error does not hide automatically
- 有一个必需的
select box
which 和 转换为select2
- 您单击提交,错误显示需要选择框。
- 您从选择 2 中选择一些选项。
- 验证错误不会自动隐藏
You can fix it with:
您可以使用以下方法修复它:
$("select").on("select2:close", function (e) {
$(this).valid();
});
回答by Adam
In Addition to ABIRAMAN's answer here is some code that
除了 ABIRAMAN 的回答,这里还有一些代码
- Makes the select2 box red when errors appear
- List the error below the select2 box
- 出现错误时使 select2 框变为红色
- 列出 select2 框下方的错误
<style>
span.error{
outline: none;
border: 1px solid #800000;
box-shadow: 0 0 5px 1px #800000;
}
</style>
<script>
$("#form").validate({
rules: {
email: "required"
},
highlight: function (element, errorClass, validClass) {
var elem = $(element);
if (elem.hasClass("select2-hidden-accessible")) {
$("#select2-" + elem.attr("id") + "-container").parent().addClass(errorClass);
} else {
elem.addClass(errorClass);
}
},
unhighlight: function (element, errorClass, validClass) {
var elem = $(element);
if (elem.hasClass("select2-hidden-accessible")) {
$("#select2-" + elem.attr("id") + "-container").parent().removeClass(errorClass);
} else {
elem.removeClass(errorClass);
}
},
errorPlacement: function(error, element) {
var elem = $(element);
if (elem.hasClass("select2-hidden-accessible")) {
element = $("#select2-" + elem.attr("id") + "-container").parent();
error.insertAfter(element);
} else {
error.insertAfter(element);
}
}
});
$('select').select2({}).on("change", function (e) {
$(this).valid()
});
</script>
回答by Himanshu Patel
Found an answer on the forums @ https://github.com/select2/select2/issues/215posted by corinnaerin. Worked perfectly for me. Sample code at http://plnkr.co/edit/4QaSguIiYsJtLpuPF8Rc?p=preview
在corinnaerin发布的论坛 @ https://github.com/select2/select2/issues/215上找到了答案。非常适合我。http://plnkr.co/edit/4QaSguIiYsJtLpuPF8Rc?p=preview 上的示例代码
var $select = $('select').select2({
placeholder: 'Choose',
allowClear: true
});
/*
* When you change the value the select via select2, it triggers
* a 'change' event, but the jquery validation plugin
* only re-validates on 'blur'
*/
$select.on('change', function() {
$(this).trigger('blur');
});
$('#myForm').validate({
ignore: 'input[type=hidden], .select2-input, .select2-focusser'
});
回答by Ken
I've found that getting Select2 to work with jQuery Validate very much depends on the markup used in creating the Select2 control.
我发现让 Select2 与 jQuery Validate 一起工作在很大程度上取决于创建 Select2 控件时使用的标记。
For the most practical use of the plugin, you'll probably be using dynamically loaded data (data obtained via web service vs. static <option/>
elements in the page). And per their spec, the way to accomplish this is by attaching Select2 to an <input type="hidden"/>
element. However, elements of type="hidden" are not validated by jQuery Validate by default.
对于插件的最实际使用,您可能会使用动态加载的数据(通过 Web 服务获得的数据与<option/>
页面中的静态元素)。而且按照他们的规范,做到这一点的方法是通过将选择二至<input type="hidden"/>
元素。但是,默认情况下,jQuery Validate 不会验证 type="hidden" 的元素。
In order to validate hidden elements using jQuery Validate, one must tinker with the ignore
property in jQuery Validate's configuration object. See the ignore
option in their spec. Try initializing the ignore
value as null
to get the validation to trigger.
为了使用 jQuery Validate 验证隐藏元素,必须修改ignore
jQuery Validate 配置对象中的属性。请参阅ignore
他们的规范中的选项。尝试初始化该ignore
值null
以触发验证。
回答by Nirav Thakar
just add a line in your validation function.
只需在验证函数中添加一行。
$('#_form_id').validate({
ignore: 'input[type=hidden]',
rules: {
//Rules
},
messages: {
//messages
},
}
回答by Robinson Legaspi
check out my code. I solve my problem by using those codes... few(css,jquery) codes only
看看我的代码。我通过使用这些代码解决了我的问题......只有几个(css,jquery)代码
$(document).ready(function() {
//form validations---------------------------------------------------------
$('#sample').validate({
ignore: [],
errorClass: "error",
errorElement: "span"
});
$("#receiver_name").select2({
placeholder: "Receiver Name"
});
$("#receiver_name").select2().change(function() {
$(this).valid();
});
});
.error .select2-choice.select2-default,
.error .select2-choices {
color: #a94442;
border-color: #a94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
}
.error:focus,
.error .select2-choice.select2-defaultLfocus,
.error .select2-choicesLfocus {
border-color: #843534;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483;
}
.select2-container .select2-choices .select2-search-field input,
.select2-container .select2-choice,
.select2-container .select2-choices,
.error {
border-radius: 1px;
}
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2-bootstrap.css" rel="stylesheet" />
</head>
<body>
<form id='sample'>
<select class="form-control" name="receiver_name[]" id="receiver_name" multiple required>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
</body>
</html>
回答by Boris Grinshpun
This doesn't work in Bootstrap Validator() because the validator includes all the inputs in the form. This means it will validate the input search field of the select2 plugin. which will interfere with the multiselect validation
这在 Bootstrap Validator() 中不起作用,因为验证器包含表单中的所有输入。这意味着它将验证 select2 插件的输入搜索字段。这会干扰多选验证
To fix this simply go to the validator.js Add the select2 input search class .select2-search__fieldto the ignore list:
要解决这个问题,只需转到 validator.js 将 select2 输入搜索类.select2-search__field 添加到忽略列表:
Validator.INPUT_SELECTOR = ':input:not([type="submit"], button, .select2-search__field):enabled:visible'
回答by denesis
To validate 'select2' inputs you first must tell jquery validate to consider hidden elements:
要验证“select2”输入,您首先必须告诉 jquery validate 考虑隐藏元素:
$.validator.setDefaults({
ignore: [],
});
This is custom highlight / unhighlight that i use for pointing select2 and tagit errors with jquery validate:
这是自定义突出显示/取消突出显示,我用于通过 jquery 验证指向 select2 和 tagit 错误:
$("#someform").validate({
rules: {
nazwa: {
required: true
},
ilosc_w_opakowaniu: {
required: "#czy_opakowanie_zbiorcze:checked"
}
},
messages: {
nazwa: "Musisz wype?ni? pole [Nazwa]",
ilosc_w_opakowaniu: "Musisz poda? ilo?? produktu w opakowaniu zbiorczym",
},
highlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).addClass( errorClass ).removeClass( validClass );
} else {
$( element ).addClass( errorClass ).removeClass( validClass );
}
// select2
if( $(element).hasClass('select2-hidden-accessible') ){
dzik = $(element).next('span.select2');
if(dzik)
dzik.addClass( errorClass ).removeClass( validClass );
}
// tagit
dzik2 = $(element).parent().find('ul.tagit')
if( dzik2.length == 1 )
dzik2.addClass( errorClass ).removeClass( validClass );
},
unhighlight: function( element, errorClass, validClass ) {
if ( element.type === "radio" ) {
this.findByName( element.name ).removeClass( errorClass ).addClass( validClass );
} else {
$( element ).removeClass( errorClass ).addClass( validClass );
}
// select2
if( $(element).hasClass('select2-hidden-accessible') ){
dzik = $(element).next('span.select2');
if(dzik)
dzik.removeClass( errorClass ).addClass( validClass );
}
// tagit
dzik2 = $(element).parent().find('ul.tagit')
if( dzik2.length == 1 )
dzik2.removeClass( errorClass ).addClass( validClass );
}
});
And some CSS:
还有一些CSS:
/** select2 error hightight **/
.select2.error .select2-selection--single{
border-color:red !important;
color:red !important;
}
/** tagit error highlight **/
.tagit.error{
border-color:red !important;
color:red !important;
}