jQuery 验证插件和 Bootstrap 4 [英] jQuery validation plugin and Bootstrap 4
问题描述
我正在使用 jQuery 验证插件来验证我的 js 表单.我也在使用 Bootstrap 4.我发现我需要修改 errorPlacement
、highlight
和 unhighlight
以使其验证错误以 BS4 样式正确显示.
I'm using jQuery validation plugin for my js form validation. I am also using Bootstrap 4. I've found that I needed to modify errorPlacement
, highlight
, and unhighlight
to make it so that the validation errors properly show up in the BS4 style.
$('#login-form').validate({
rules: {
login_username: {
required: true
},
login_password: {
required: true
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
submitHandler: function (form) {
neou_cms.remove_error_messages();
var username = form.elements['login_username'].value;
var password = CryptoJS.SHA512(form.elements['login_password'].value).toString();
login.login_user(username, password);
}
});
因此,对于每个函数,我发现自己都在重复这些属性.有没有办法扩展"验证库,这样我就不必每次都重复 errorPlacement
、highlight
和 unhighlight
代码我使用验证的时间?
Thus for every function I find myself repeating those properties. Is there a way of "extending" the validation library so that I don't have to repeat the errorPlacement
, highlight
, and unhighlight
code every time I use validate?
推荐答案
解决方案:
https://jqueryvalidation.org/jQuery.validator.setDefaults/
jQuery.validator.setDefaults({
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
这篇关于jQuery 验证插件和 Bootstrap 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!