Javascript jQuery 验证 - 获取 invalidHandler 中错误字段的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11640189/
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 Validation - get list of erroneous fields in invalidHandler
提问by jdavis
I'm using jQuery Validation on a page. During the call to the invalidHandler I would like to be able to access a list of all the form elements that failed validation.
我在页面上使用 jQuery 验证。在调用 invalidHandler 期间,我希望能够访问验证失败的所有表单元素的列表。
This function is being passed as one of the options to the jQuery.validate() method...
此函数作为选项之一传递给 jQuery.validate() 方法...
invalidHandler: function (form) {
var validator = $("#AddEditFinancialInstitutionForm").validate();
validator.showErrors();
console.log(validator);
}
I'm trying to find this information somewhere in the resulting validator object, but I can't seem to find it. Is there another way I can access this information?
我试图在生成的验证器对象中的某处找到此信息,但我似乎无法找到它。还有其他方法可以访问这些信息吗?
Thanks
谢谢
回答by Ryley
In the invalidHandler
, you are passed two arguments, a jQuery.Event
and the validator
object. You don't need to call validate within your invalidHandler to get the validate object. Further, the validator object has a properties called errorList
and errorMap
, which contain the information you are looking for.
在 中invalidHandler
,你被传递了两个参数,ajQuery.Event
和validator
对象。您不需要在 invalidHandler 中调用 validate 来获取验证对象。此外,验证器对象有一个名为errorList
and的属性errorMap
,其中包含您要查找的信息。
invalidHandler: function(e,validator) {
//validator.errorList contains an array of objects, where each object has properties "element" and "message". element is the actual HTML Input.
for (var i=0;i<validator.errorList.length;i++){
console.log(validator.errorList[i]);
}
//validator.errorMap is an object mapping input names -> error messages
for (var i in validator.errorMap) {
console.log(i, ":", validator.errorMap[i]);
}
}
回答by Jules
If you are using the default error class and only find the invalid elements, use
如果您使用默认错误类并且只找到无效元素,请使用
$(this).find("input.error") // inside invalidHandler
回答by user3732708
use this for getting errored field's whole element and it's attributes.
使用它来获取错误字段的整个元素及其属性。
var formerrorList = $("#FORM_ID_HERE").data("validator").errorList;
$.each(formerrorList, function (key, value) {
console.log(formerrorList[key].element.id);
});