问题
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.
The basic 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>
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>
回答1:
You should use classHandler
instead of errorClass
.
This should work:
$(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>',
});
});
You can also check this related answer here on SO: parsley 2.0.3 not working with boostrap 3
来源:https://stackoverflow.com/questions/25594278/parsley-js-add-error-success-class-to-parent