我正在尝试使用jQuery Validation Plugin为我的表单添加验证,但是我遇到了一个问题,当我使用输入组时,插件会输出错误消息。
$('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');
}
});
答案 0 :(得分:340)
为了与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);
}
}
});
答案 1 :(得分:85)
为了与Bootstrap 3完全兼容,我添加了对输入组,无线电和复选框的支持,这在其他解决方案中是缺失的。
2017年10月20日更新:检查了其他答案的建议,并为无线电内联的特殊标记添加了额外支持,为一组无线电提供了更好的错误放置或复选框,并添加了对自定义 .novalidation 类的支持,以防止对控件进行验证。希望这有助于并感谢您的建议。
包含验证插件后,添加以下调用:
$.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);
}
}
});
这适用于所有Bootstrap 3表单类。如果使用水平形式,则必须使用以下标记。这可确保 help-block 文本尊重 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>
答案 2 :(得分:22)
我使用仅使用Twitter Bootstrap 3设计的表单。我为validor设置默认函数,并仅运行带有规则的validate方法。我使用FontAweSome中的图标,但您可以在doc示例中使用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>');
}
}
});
完成。运行验证功能后:
$("#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"
}
}
});
答案 3 :(得分:10)
在上面的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');
}
答案 4 :(得分:8)
这是您需要的解决方案,您可以使用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');
}
});
它对我来说就像魔法一样。 干杯
答案 5 :(得分:4)
以下是我在向表单添加验证时使用的内容:
// 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'
});
当使用jquery验证库时,这对我有用于Bootstrap 3样式。
答案 6 :(得分:3)
我用这个用于收音机:
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);
}
这样,错误显示在最后一个无线电选项下。
答案 7 :(得分:3)
我知道这个问题是针对Bootstrap 3的,但是因为一些Bootstrap 4相关的问题被重定向到这个重复项,这里是与Bootstrap 4兼容的代码片段:
$.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);
}
},
});
一些差异是:
has-danger
代替has-error
答案 8 :(得分:2)
对于bootstrap 4 beta,alpha和beta版本的bootstrap(以及bootstrap 3)之间有一些重大变化,尤其是。关于表单验证。
首先,要正确放置图标,您需要添加样式,这相当于引导程序3中的内容,而不再是引导程序4 beta ...这里是我使用的内容<\ n / p>
.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;
}
由于测试版使用的是“状态”,因此课程也发生了变化。控件而不是您发布的代码没有反映的类,因此您的上述代码可能无法正常工作。无论如何,您需要添加“经过验证的”#39;在成功或突出显示/取消强调回调
中对表格进行分类$(element).closest('form').addClass('was-validated');
我还建议将新元素和类用于表单控件帮助文本
errorElement: 'small',
errorClass: 'form-text invalid-feedback',
答案 9 :(得分:2)
对于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);
}
}
});
希望这会有所帮助!
答案 10 :(得分:1)
这构成了字段
$("#form_questionario").validate({
debug: false,
errorElement: "span",
errorClass: "help-block",
highlight: function (element, errorClass, validClass) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.form-group').removeClass('has-error');
},
errorPlacement: function (error, element) {
if (element.parent('.input-group').length || element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
error.insertBefore(element.parent());
} else {
error.insertAfter(element);
}
},
// Specify the validation rules
rules: {
'campo1[]': 'required',
'campo2[]': 'required',
'campo3[]': 'required',
'campo4[]': 'required',
'campo5[]': 'required'
},
submitHandler: function (form) {
form.submit();
}
});
答案 11 :(得分:0)
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('span.glyphicon').remove();
$(element).closest('.form-group').append('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
}
},
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('span.glyphicon').remove();
$(element).closest('.form-group').append('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
}
}
});
答案 12 :(得分:0)
尝试使用此示例代码。使用Jquery验证插件和其他方法。 这是我的项目的工作代码。希望这对您有帮助
//jquery validation booking page
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='book']").validate({
//on key up validation
onkeyup: function(element) {
$(element).valid();
},
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
fname: {
required: true,
lettersonly: true
},
lname:{
required: true,
lettersonly: true
},
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
fname: {
required:"Please enter your firstname",
lettersonly:"Letters allowed only"
},
lname: {
required:"Please enter your lastname",
lettersonly:"Letters allowed only"
},
email: "Please enter a valid email address"
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
.error {
color: red;
margin-left: 5px;
font-size:15px;
}
<script src="design/bootstrap-3.3.7-dist/js/jquery.validate.js"></script>
<script src="design/bootstrap-3.3.7-dist/js/additional-methods.js"></script>
<form name="book" id="book" action="" method="post">
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="fname">First Name</label>
<input type="text" name="fname" id="fname" class="form-control" placeholder="First Name">
</div>
<div class="col-md-6">
<label class="" for="lname">Last Name</label>
<input type="text" name="lname" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="row form-group">
<div class="col-md-6 ">
<label class="" for="date">Date</label>
<input type="text" id="date" class="form-control datepicker px-2" placeholder="Date of visit">
</div>
<div class="col-md-6">
<label class="" for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Email">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="treatment">Service You Want</label>
<select name="treatment" id="treatment" class="form-control">
<option value="">Hair Cut</option>
<option value="">Hair Coloring</option>
<option value="">Perms and Curls</option>
<option value="">Hair Conditioning</option>
<option value="">Manicure</option>
<option value="">Pedicure</option>
<option value="">Nails Extension</option>
<option value="">Nail Design</option>
<option value="">Waxing Eyebrows</option>
<option value="">Waxing Hands/Legs</option>
<option value="">Full Face Waxing</option>
<option value="">Full Body/Body Parts Wax</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="" for="note">Notes</label>
<textarea name="note" id="note" cols="30" rows="5" class="form-control" placeholder="Write your notes or questions here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<center><input type="submit" value="Book Now" class="btn btn-primary btn-lg"></center>
</div>
</div>
</form>
答案 13 :(得分:-1)
另一个选择是提前在表单组之外放置一个错误容器。验证员将在必要时使用它。
<div class="form-group">
<label class="control-label" for="new-task-due-date">When is the task due?</label>
<div class="input-group date datepicker">
<input type="text" id="new-task-due-date" class="required form-control date" name="dueDate" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<label for="new-task-due-date" class="has-error control-label" style="display: none;"></label>
</div>