twitter-bootstrap Bootstrap 选择插件不适用于 jQuery 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21018970/
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
Bootstrap select Plugin Not work With jQuery Validation
提问by ?_?
I design my HTMLselectbox using bootstrap select plugin. Now, i add jQueryvalidationPlugin for validatemy form But, Validation form not work with bootstrap select plugin.
我HTML使用bootstrap select plugin设计我的选择框。现在,我为我的表单添加了jQueryvalidation插件validate但是,验证表单不适用于引导选择插件。
DEMO HERE
演示在这里
HTML:
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
<br/>
<input type="submit" />
</form>
JS:
JS:
$(document).ready(function () {
$('select').selectpicker();
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
NOTE:For check this conflict, remove Line 2 from JS, jQuery Validation Worked.
笔记:For check this conflict, remove Line 2 from JS, jQuery Validation Worked.
EDIT:adeneoFix Problem Using ignore[]method : FIDDLE
编辑:adeneo修复问题使用ignore[]方法:FIDDLE
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
Now This Worked but I have New Problem: In normal Validation after select fields, error message This field is requiredauto Hide( OR with add any css, show success message) but Now, error message is show after fix required field. in act: when we choose years, error message not hide.
现在这有效,但我有新问题:在选择字段后的正常验证中,错误消息This field is required自动隐藏(或添加任何 css,显示成功消息)但现在,在修复所需字段后显示错误消息。实际操作:当我们选择年份时,错误信息不会隐藏。
How do fix This?
如何解决这个问题?
采纳答案by adeneo
The select plugin hides the original select and creates a new one with an unordered list that updates the hidden selects value, but hidden elements are not validated by default by the validation plugin, you have to use the ignore rule and turn on validation for hidden elements
select 插件隐藏了原来的 select 并创建了一个带有更新隐藏 selects 值的无序列表的新选择,但是默认情况下验证插件不会验证隐藏元素,您必须使用 ignore 规则并打开对隐藏元素的验证
$('#myform').data("validator").settings.ignore = "";
or
或者
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
The Bootstrap select plugin creates a new dropdown from an unordered list, and the original select is hidden and it's value is updated when the user interacts with the unordered list.
Bootstrap 选择插件从无序列表创建一个新的下拉列表,原始选择被隐藏,当用户与无序列表交互时,它的值会更新。
This has the disadvantange of also moving the error message, as the original, now hidden select is the element being validated, and the new visible dropdown made up of an unordered list is inserted by Bootstrap below the original select in the DOM, the error message is inserted after the original select, but before the unordered list, so it appears above the custom dropdown, not below it like it would if the original select was used.
这具有也会移动错误消息的缺点,因为原始的,现在隐藏的选择是正在验证的元素,并且由无序列表组成的新可见下拉列表由 Bootstrap 在 DOM 中的原始选择下方插入,错误消息插入在原始选择之后,但在无序列表之前,因此它出现在自定义下拉列表上方,而不是像使用原始选择时那样位于其下方。
To fix it you can move the error message for any given element rather easily
要修复它,您可以很容易地移动任何给定元素的错误消息
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
回答by techknowcrat
I had a similar issue so here's how I kind of extended @adeneo's answer together with lessons learnt from (the post here).
我有一个类似的问题,所以这里是我如何扩展@adeneo的答案以及从(这里的帖子)中吸取的教训。
Note: For those who bump into this post, please read @adeneo's answer and (the post here)to understand the scope of this solution.
The resulting code that very well functions flawlessly for me looks as follows:
对我来说运行良好的结果代码如下所示:
jQuery / javascript:
jQuery / javascript:
$(document).ready(function() {
$.validator.setDefaults({
/*OBSERVATION (1): note the options used for "ignore"*/
ignore: ':not(select:hidden, input:visible, textarea:visible)',
/*...other options omitted to focus on the OP...*/
errorPlacement: function (error, element) {
/*OBSERVATION (2): note how selection is on the class "selectpicker"*/
if (element.hasClass('selectpicker')) {
error.insertAfter('.bootstrap-select');
} else {
error.insertAfter(element);
}
/*Add other (if...else...) conditions depending on your
* validation styling requirements*/
}
});
$('#myform').validate({
rules: {
'year': {
required: true
}
},
messages: {
'year': {
required: 'Please select a year from the dropdown'
}
}
});
});
HTML:
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select><br/>
<input type="submit" />
</form>
Explanation:
解释:
OBSERVATION (1):ignore: ':not(select:hidden, input:visible, textarea:visible)'simply means to ignore validation for all elements that's not a hidden <select>, that's not a visible <input>and that's not a visible <textarea>.
观察(1):ignore: ':not(select:hidden, input:visible, textarea:visible)'简单的意思是忽略对所有不是 hidden <select>、不是 visible<input>和不是 visible 的元素的验证<textarea>。
In simpler English, it just says to validate hidden <select>, ignore hidden <input>and ignore hidden <textarea>which is what we usually want in many cases. This I think is a better way to target what validation should be ignored or not.
在简单的英语中,它只是说验证隐藏<select>,忽略隐藏<input>和忽略隐藏<textarea>,这是我们在许多情况下通常想要的。我认为这是一种更好的方法来定位哪些验证应该被忽略或不应该被忽略。
Based on @Alvin Lee's answer here, setting the ignoreoptions on the form element as follows was ok, but had its caveats;
根据@Alvin Lee在此处的回答,将ignore表单元素上的选项设置如下是可以的,但有其警告;
$('#myform').validate().settings.ignore =
':not(select:hidden, input:visible, textarea:visible)';
The Problem:The bootstrap select element got validated but showed the default message This field is requiredon every other input element instead of overriding it with all the custom validation messages that were previously configured.
问题:引导选择元素得到验证,但This field is required在每个其他输入元素上显示默认消息,而不是用之前配置的所有自定义验证消息覆盖它。
The fix:move the ignoresetting into $.validator.setDefaults({...})block... Voila! ! !
解决方法:将ignore设置移动到$.validator.setDefaults({...})块中...瞧!!!
OBSERVATION (2):
观察(2):
Instead of doing if (element.attr("name") == "year") {...}like @adeneopointed, I rather decided to select on class='selectpicker'... then in the javascript, check if the element had this class by doing if (element.hasClass('selectpicker')) {...}. This just ensures that this rule can be applied to all bootstrap-select elements as long as they're decorated with the class selectpicker.
我没有if (element.attr("name") == "year") {...}像@adeneo指出的那样做,而是决定选择 on class='selectpicker'... 然后在 javascript 中,通过执行if (element.hasClass('selectpicker')) {...}. 这只是确保此规则可以应用于所有引导选择元素,只要它们用 class 修饰即可selectpicker。
Hope this is clear enough and helpful to somebody who has similar issues!
希望这足够清楚并且对有类似问题的人有所帮助!
回答by Vladislav Kostenko
If you use 'selectpicker' class to initialize bootstrap-select widget, I recommend to partially solve the issue via changing default ignore settings for jquery validate:
如果您使用“selectpicker”类来初始化 bootstrap-select 小部件,我建议通过更改 jquery 验证的默认忽略设置来部分解决该问题:
$.validator.setDefaults({ ignore: ':hidden:not(.selectpicker)' });
before you validate your form. This is a bit better approach, and you also need to move error messages as adeneosupposed. And still it will not have a similar validation behavior as select would have. The problem arise when the parent container is hidden. In case you do not use bootstrap-select your select will not validate when container is hidden, but when you use it still validates.
在您验证表单之前。这是一种更好的方法,您还需要按照adeneo 的假设移动错误消息。而且它仍然不会像 select 那样具有类似的验证行为。隐藏父容器时会出现问题。如果您不使用 bootstrap-select 您的选择将不会在容器隐藏时验证,但当您使用它时仍然会验证。

