我尝试使用 jquery validate 来显示从服务器返回的一些错误。
我正在使用 validator.showErrors() 方法来执行此操作。
我可以让该方法按照示例 here 工作。 .
var validator = $("#myform").validate();
validator.showErrors({"firstname": "I know that your firstname is Pete, Pete!"});
但是,我想要实现的目标是对相同或不同的字段出现 2 个或更多验证错误。根据文档这是可能的
Show the specified messages. Keys have to refer to the names of elements, values are displayed for those elements, using the configured error placement.
Arguments:
errors
Object<String, String>
One or more key/value pairs of input names and messages.
查看 showErrors 方法内部会显示以下内容:
showErrors: function(errors) {
if(errors) {
// add items to error list and map
$.extend( this.errorMap, errors );
this.errorList = [];
for ( var name in errors ) {
this.errorList.push({
message: errors[name],
element: this.findByName(name)[0]
});
}
// remove items from success list
this.successList = $.grep( this.successList, function(element) {
return !(element.name in errors);
});
}
this.settings.showErrors
? this.settings.showErrors.call( this, this.errorMap, this.errorList )
: this.defaultShowErrors();
}
我尝试过以下方法:
validator.showErrors({ "Id": "I know that your firstname is Pete, Pete!" },{ "Id":"test2"});
但它仍然只显示第一个错误。
知道使用正确的格式来显示多个错误
最佳答案
所以正确的格式是
validator.showErrors({ "Id": ["I know that your firstname is Pete", "test2" ]});
不幸的是,第二个错误显示在第一个错误旁边,因此我的下一个问题是找到一种更好的方法来格式化这些错误。
关于jquery 验证显示多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603327/