javascript 使用 jQuery Validate 的 invalidHandler 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4616947/
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
Using jQuery Validate's invalidHandler event
提问by mhenry
I need to add a class to div that is wrapped around the select element upon validation.
我需要向 div 添加一个类,该类在验证时围绕 select 元素。
$("#Form").validate({
invalidHandler: function (form, validator) {
$("[id$='_DropDownList']").each(function () {
// How do I figure out if $(this) is valid or invalid?
// Add the class below if invalid.
$(this).parent().addClass("error");
});
}
});
回答by Nick Craver
You can use the .valid()method, like this:
您可以使用该.valid()方法,如下所示:
$("#Form").validate({
invalidHandler: function (form, validator) {
$("[id$='_DropDownList']").each(function () {
if(!$(this).valid())
$(this).parent().addClass("error");
});
}
});
However, the highlightand unhightlightoptionsare specifically for this:
但是,highlight和unhightlight选项专门用于此:
$("#Form").validate({
highlight: function(element, errorClass, validClass) {
$(element).parent().removeClass(validClass).addClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent().removeClass(errorClass).addClass(validClass);
}
});
回答by Supreme Dolphin
invalidHandleris only called when the form is submitted and not valid. I believe adding your code under that function alone is enough.
invalidHandler仅在表单提交且无效时调用。我相信仅在该功能下添加您的代码就足够了。
回答by timharris777
It looks like this code is correct:
看起来这段代码是正确的:
$(this).parent().addClass("error");
Maybe your issue is with the code surrounding it... Try moving your addClass line outside the function it is in to see if it work there.
也许你的问题是围绕它的代码......尝试将你的 addClass 行移到它所在的函数之外,看看它是否在那里工作。

