twitter-bootstrap 带有 jQuery 验证插件的 Bootstrap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18754020/
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 with jQuery Validation Plugin
提问by Miguel Borges
I am trying to add validation to my form with jQuery Validation Plugin, but I'm having a problem where the plugin puts the error messages when I'm using input groups.
我正在尝试使用 jQuery 验证插件向我的表单添加验证,但是我遇到了一个问题,即当我使用输入组时插件会放置错误消息。


$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
My code:http://jsfiddle.net/hTPY7/4/
我的代码:http : //jsfiddle.net/hTPY7/4/
回答by Miguel Borges
for total compatibility with twitter bootstrap 3, I need to override some plugins methods:
为了与 twitter bootstrap 3 完全兼容,我需要覆盖一些插件方法:
// override jquery validate plugin defaults
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
See Example: http://jsfiddle.net/mapb_1990/hTPY7/7/
回答by Andreas Krohn
For full compatibility with Bootstrap 3 I added support for input-group, radioand checkbox, that was missing in the other solutions.
为了与 Bootstrap 3 完全兼容,我添加了对input-group、radio和checkbox 的支持,这在其他解决方案中是缺失的。
Update 10/20/2017: Inspected suggestions of the other answers and added additional support for special markup of radio-inline, better error placement for a group of radios or checkboxes and added support for a custom .novalidationclass to prevent validation of controls. Hope this helps and thanks for the suggestions.
2017 年 10 月 20 日更新:检查了其他答案的建议,并添加了对radio-inline特殊标记的额外支持,为一组收音机或复选框更好地放置错误,并添加了对自定义.novalidation类的支持以防止验证控件。希望这会有所帮助并感谢您的建议。
After including the validation plugin add the following call:
包含验证插件后,添加以下调用:
$.validator.setDefaults({
errorElement: "span",
errorClass: "help-block",
highlight: function (element, errorClass, validClass) {
// Only validation controls
if (!$(element).hasClass('novalidation')) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
}
},
unhighlight: function (element, errorClass, validClass) {
// Only validation controls
if (!$(element).hasClass('novalidation')) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
}
},
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
}
else if (element.prop('type') === 'radio' && element.parent('.radio-inline').length) {
error.insertAfter(element.parent().parent());
}
else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
error.appendTo(element.parent().parent());
}
else {
error.insertAfter(element);
}
}
});
This works for all Bootstrap 3 form classes. If you use a horizontal form you have to use the following markup. This ensures that the help-blocktext respects the validation states ("has-error", ...) of the form-group.
这适用于所有 Bootstrap 3 表单类。如果您使用水平表格,则必须使用以下标记。这确保帮助块文本尊重form-group的验证状态(“has-error”,...)。
<div class="form-group">
<div class="col-lg-12">
<div class="checkbox">
<label id="LabelConfirm" for="CheckBoxConfirm">
<input type="checkbox" name="CheckBoxConfirm" id="CheckBoxConfirm" required="required" />
I have read all the information
</label>
</div>
</div>
</div>
回答by DARK_DIESEL
I use forms designed only with Twitter Bootstrap 3. I set defaults functions for validor and run only validate method with rules. I use Icons from FontAweSome, but you can use Glyphicons as in doc example.
我使用仅使用 Twitter Bootstrap 3 设计的表单。我为验证器设置了默认函数,并仅运行带有规则的验证方法。我使用 FontAweSome 中的图标,但您可以使用文档示例中的 Glyphicons。


jQuery.validator.setDefaults({
highlight: function (element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');
$(element).closest('.form-group').find('i.fa').remove();
$(element).closest('.form-group').append('<i class="fa fa-exclamation fa-lg form-control-feedback"></i>');
}
},
unhighlight: function (element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');
$(element).closest('.form-group').find('i.fa').remove();
$(element).closest('.form-group').append('<i class="fa fa-check fa-lg form-control-feedback"></i>');
}
}
});
Done. After run validate function:
完毕。运行验证功能后:
$("#default-register-user").validate({
rules: {
'login': {
required: true,
minlength: 5,
maxlength: 20
},
'email': {
required: true,
email: true,
minlength: 5,
maxlength: 100
},
'password': {
required: true,
minlength: 6,
maxlength: 25
},
'confirmpassword': {
required: true,
minlength: 5,
maxlength: 25,
equalTo: "#password"
}
}
});
回答by Jose Apollo
Adding onto Miguel Borges answer above you can give the user that green success feedback by adding the following line to in the highlight/unhighlight code block.
添加到上面的 Miguel Borges 答案中,您可以通过在突出显示/取消突出显示代码块中添加以下行来向用户提供绿色成功反馈。
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
}
回答by Drixson Ose?a
this is the solution you need, you can use the errorPlacementmethod to override where to put the error message
这是您需要的解决方案,您可以使用该errorPlacement方法来覆盖放置错误消息的位置
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
errorPlacement: function(error, element) {
error.insertAfter('.form-group'); //So i putted it after the .form-group so it will not include to your append/prepend group.
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
it's works for me like magic. Cheers
它对我来说就像魔法一样。干杯
回答by Edwin Perez
Here is what I use when adding validation to form:
这是我在向表单添加验证时使用的内容:
// Adding validation to form.
$(form).validate({
rules: {
title: {
required: true,
minlength: 3,
},
server: {
ipAddress: true,
required: true
}
},
highlight: function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
success: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success');
},
errorClass: 'help-block'
});
This worked for me for Bootstrap 3 styling when using the jquery validation library.
在使用 jquery 验证库时,这对我的 Bootstrap 3 样式有用。
回答by Jehad Ahmad Jaghoub
for bootstrap 4 this work with me good
对于 bootstrap 4,这对我很好
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
},
unhighlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
$(element).closest('.form-group').find(".form-control:first").addClass('is-valid');
},
errorElement: 'span',
errorClass: 'invalid-feedback',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
hope it will help !
希望它会有所帮助!
回答by martpie
I know this question is for Bootstrap 3, but as some Bootstrap 4 related question are redirected to this one as duplicates, here's the snippet Bootstrap 4-compatible:
我知道这个问题是针对 Bootstrap 3 的,但是由于一些与 Bootstrap 4 相关的问题被重定向到这个问题作为重复,这里是 Bootstrap 4-compatible 的片段:
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-danger');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-danger');
},
errorElement: 'small',
errorClass: 'form-control-feedback d-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if(element.prop('type') === 'checkbox') {
error.appendTo(element.parent().parent().parent());
} else if(element.prop('type') === 'radio') {
error.appendTo(element.parent().parent().parent());
} else {
error.insertAfter(element);
}
},
});
The few differences are:
几个区别是:
- The use of class
has-dangerinstead ofhas-error - Better error positioning radios and checkboxes
- 使用类
has-danger代替has-error - 更好的错误定位无线电和复选框
回答by Marcel Overdijk
I used this for radio's:
我将它用于收音机:
if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
error.appendTo(element.parent().parent());
}
else if (element.parent(".input-group").length) {
error.insertAfter(element.parent());
}
else {
error.insertAfter(element);
}
this way the error is displayed under last radio option.
这样错误就会显示在最后一个单选选项下。
回答by user2030404
For the bootstrap 4 beta were some big changes between the alpha and beta versions of bootstrap (and also bootstrap 3), esp. in regards to form validation.
对于 bootstrap 4 beta,bootstrap(以及 bootstrap 3)的 alpha 和 beta 版本之间有一些重大变化,尤其是。关于表单验证。
First, to place the icons correctly you'll need to add styling which equates to what was in bootstrap 3 and no longer in bootstrap 4 beta...here's what I'm using
首先,要正确放置图标,您需要添加样式,它等同于 bootstrap 3 中的样式,而不再是 bootstrap 4 beta 中的样式……这就是我正在使用的
.fa.valid-feedback,
.fa.invalid-feedback {
position: absolute;
right: 25px;
margin-top: -50px;
z-index: 2;
display: block;
pointer-events: none;
}
.fa.valid-feedback {
margin-top: -28px;
}
The classes have also changed as the beta uses the 'state' of the control rather than classes which your posted code doesn't reflect, so your above code may not work. Anyway, you'll need to add 'was-validated' class to the form either in the success or highlight/unhighlight callbacks
由于测试版使用控件的“状态”而不是您发布的代码未反映的类,因此类也发生了变化,因此您的上述代码可能不起作用。无论如何,您需要在成功或突出显示/取消突出显示回调中向表单添加“已验证”类
$(element).closest('form').addClass('was-validated');
I would also recommend using the new element and classes for form control help text
我还建议将新元素和类用于表单控件帮助文本
errorElement: 'small',
errorClass: 'form-text invalid-feedback',

