jQuery验证插件自定义错误类分配给父div [英] jquery validate plugin custom error class assigned to parent div
问题描述
我有一个表单,可以通过jQuery进行即时验证以验证插入.
I have a form that Im validating with jQuery validate pluging.
这是我用于验证的jQuery代码:
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) { }
});
我添加了一个errorClass,需要将其附加到父div,而不是输入字段:
I have added an errorClass that I need to append to a parent div, not to the input field:
其中一个字段的HTML结构如下:
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>
如果您发现"invalid
"类已经附加到实际上是正确的输入元素上,但是我需要将其附加到我的<div class="form-group form-group-custom">
上,并在验证正常时将其删除.
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.
推荐答案
highlight
和当事物变为有效/无效时,unhighlight
函数始终用于应用/删除任何类.只需编写以您的父div
为目标的自定义jQuery DOM遍历函数.
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');
},
这篇关于jQuery验证插件自定义错误类分配给父div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!