Jquery 验证插件如何将错误类添加到标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14627317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery validate plugin how to add error class to label
提问by Strontium_99
Using the jquery validate plugin and I'm trying to override it's default behavior. this is an example of my html:
使用 jquery 验证插件,我试图覆盖它的默认行为。这是我的 html 的一个例子:
<table>
<tr>
<td>
<label for="my-input>Name</label>
</td>
</tr>
<tr>
<td>
<input type="text" class="required" id="my-input />
</td>
</tr>
</table>
All I want the valadate to do is add the class .error to the existing label, and then remove it once the field passes validation.
我想让 valadate 做的就是将类 .error 添加到现有标签,然后在字段通过验证后将其删除。
Thanks.
谢谢。
回答by Dr Blowhard
this is the default behaviour, you just need to stop the error message being displayed on the page. You can do this by overriding errorPlacement
这是默认行为,您只需要停止页面上显示的错误消息。您可以通过覆盖 errorPlacement 来做到这一点
$('form').validate({
errorPlacement: function () { }
});
EDIT.
编辑。
sorry misread the question bit - the code below works but there is probably a better way
抱歉误读了问题位 - 下面的代码有效,但可能有更好的方法
$('form').validate({
// make sure error message isn't displayed
errorPlacement: function () { },
// set the errorClass as a random string to prevent label disappearing when valid
errorClass : "bob",
// use highlight and unhighlight
highlight: function (element, errorClass, validClass) {
$(element.form).find("label[for=" + element.id + "]")
.addClass("error");
},
unhighlight: function (element, errorClass, validClass) {
$(element.form).find("label[for=" + element.id + "]")
.removeClass("error");
}
});
the above code comes from the highlight example on the options docs
上面的代码来自选项文档上的突出显示示例
回答by SpareMe
errorElement: "label",
errorPlacement: function(error, element) {
error.insertBefore(element.parent().children("br"));
},
highlight: function(element) {
$(element).parent().addClass("error");
},
unhighlight: function(element) {
$(element).parent().removeClass("error");
}