我已经创建了一个jquery验证器插件的方法,它的工作原理就像远程规则。不同之处在于我想显示动态错误消息(基于ajax响应)。
jQuery.validator.addMethod("duplicate",function(value,element,params) {
var object_settings = this.settings;
params.data[$(element).attr("name")] = value;
$.post(params.url,params.data,function(response) {
if (response == 'true'){ return true; }
else {
object_settings.messages[element.name] = response;
return false;
}
},'text');
},'');
它的工作原理… ….它设置消息,但最初不显示(如果您再次验证字段,则显示消息)。
有什么建议么?
(也许远程规则提供这个功能…我在文档中找不到任何东西)
解决方法
这里的解决方案….需要调用该对象的showErrors函数:
jQuery.validator.addMethod("duplicate",params) {
var validator = this;
params.data[element.name] = value;
$.post(params.url,function(response) {
if (response == 'true'){ return true; }
else {
var errors = {};
errors[element.name] = response;
validator.showErrors(errors);
return false;
}
},'');
取自jquery.validate.js中的“remote”(第917 – 919行)