我使用以下代码在jquery验证插件的add方法中显示自定义消息。我引用了这个链接:http://www.mainframes.co.uk/index.php/2011/04/07/jquery-form-validator-custom-validation-method-using-addmethod-for-validating-date-of-birth-dob/
$.validator.addMethod("nameId",function(value,element){
var result = true;
//check if pattern matches
var pattern = new RegExp(<pattern>);
if(pattern.test(value)){
//get availability via ajax call
$.ajaxSetup({
async: false,
"error":function() {
alert("error");
}});
$.getJSON("<url>",
{
param: value
},
function(data) {
if(condition){
result = true;
}else{
$.validator.messages.nameId = "Msg 1";
result = false;
}
});
}else{
$.validator.messages.nameId = "Msg 2";
result = false;
}
return result;
},"");
验证时不会显示任何错误。上面可能有什么不对......
答案 0 :(得分:1)
如果将.getJSON调用放在.ajaxSetup的成功回调函数中会发生什么?像这样:
$.validator.addMethod("nameId",function(value,element){
var result = true;
var pattern = new RegExp(<pattern>);
if(pattern.test(value)){
//get availability via ajax call
$.ajaxSetup({
async: false,
"success": function() {
$.getJSON("<url>",
{
param: value
},
function(data) {
if(condition){
result = true;
}else{
$.validator.messages.nameId = "Msg 1";
result = false;
}
});
},
"error":function() {
alert("error");
}
});
}else{
$.validator.messages.nameId = "Msg 2";
result = false;
}
return result;
},"");
答案 1 :(得分:1)
在返回结果行之前添加此内容:
$.validator.messages.myvalidator = customError;
答案 2 :(得分:-1)
您无法在验证方法中进行异步回调。