问题描述
我正在使用Parsley JS()进行表单验证。错误的默认行为是向每个无效输入添加一个 parsley-error
类。但是,我想更改默认行为并将错误类添加到输入的父级 - 特别是在 form-group
元素上。
I'm using Parsley JS (http://parsleyjs.org/) for form validation. The default behavior for errors is to add a class of parsley-error
to each invalid input. However, I'd like to change up the default behavior and add the error class to the parent of the input - specifically on the form-group
element.
基本HTML
<form class="js-contact-form">
<!-- this field is just required, it would be validated on form submit -->
<div class="form-group">
<label for="fullname">Full Name * :</label>
<input type="text" class="form-control" name="fullname" placeholder="Name" required />
</div>
<!-- this required field must be an email, and validation will be run on field change -->
<div class="form-group">
<label for="email">Email * :</label>
<input type="email" class="form-control" name="email" data-parsley-trigger="change" />
</div>
<input type="submit" />
</form>
我正在使用Javascript安装来初始化所有内容,我尝试覆盖errorClass和successClass选项有我自己的功能,但似乎不起作用。
I'm using the "Javascript Installation" to initialize everything and I tried overriding the "errorClass" and "successClass" options with my own function, but doesn't seem to work.
$('.js-contact-form').parsley({
trigger: 'change',
errorClass: function(){
$(this).parent()
.removeClass('has-success')
.addClass('has-error has-feedback');
},
successClass: function(){
$(this).parent()
.removeClass('has-error')
.addClass('has-success has-feedback');
},
errorsWrapper: '<div class="invalid-message"></div>',
errorTemplate: '<span></span>',
});
我想最终得到这样的结果:
I want to end up with something like this:
<div class="form-group has-feedback has-error">
<label for="fullname">Full Name * :</label>
<input type="text" class="form-control" name="fullname" placeholder="Name" required />
<div class="invalid-message">
<span>This field is required</span>
</div>
</div>
推荐答案
你应该使用 classHandler
而不是 errorClass
。
这应该有效:
$(document).ready(function() {
$('.js-contact-form').parsley({
trigger: 'change',
successClass: "has-success",
errorClass: "has-error",
classHandler: function (el) {
return el.$element.closest('.form-group'); //working
},
errorsWrapper: '<div class="invalid-message"></div>',
errorTemplate: '<span></span>',
});
});
您还可以在SO上查看此相关答案:
You can also check this related answer here on SO: parsley 2.0.3 not working with boostrap 3
这篇关于Parsley JS将错误/成功类添加到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!