问题
I have a form that Im validating with jQuery validate pluging.
This is my jQuery code for validating:
$('#authForm').validate({
rules: {
Email: {
required: true,
email: true
},
Password: {
required: true
},
PasswordAgain: {
equalTo: "#Password"
},
Name: {
required: true
}
},
errorClass: "invalid",
errorPlacement: function(error, element) { }
});
I have added an errorClass that I need to append to a parent div, not to the input field:
The HTML structure of one of the fields are like this:
<div class="form-group form-group-custom ">
<label>Email Address</label>
<input name="Email" type="text" class="form-control invalid" value="test@test.com" aria-required="true" aria-describedby="Email-error" aria-invalid="true">
</div>
And if you notice the "invalid" class has been appended to the input element that actually is correct, but I need to append it to my <div class="form-group form-group-custom"> and also remove it when the validation is ok.
回答1:
The highlight and unhighlight functions are always used to apply/remove any classes when things go valid/invalid. Simply write custom jQuery DOM traversal functions that target your parent div.
$('#authForm').validate({
rules: {
....
},
....
highlight: function(element, errorClass, validClass) {
$(element).parent('div').addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('div').addClass(validClass).removeClass(errorClass);
},
....
If the classes need to be completely separate from the classes that are automatically applied by the plugin, then instead of using the keywords that represent the pre-set classes, use different classes renamed as you wish.
highlight: function(element, errorClass, validClass) {
$(element).parent('div').addClass('myerrorclass').removeClass('myvalidclass');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('div').addClass('myvalidclass').removeClass('myerrorclass');
},
来源:https://stackoverflow.com/questions/37515146/jquery-validate-plugin-custom-error-class-assigned-to-parent-div