有用的参考资料:
- jQuery 验证:更改默认错误消息
- http://jqueryvalidation.org/jQuery.validator.addMethod
- http://jqueryvalidation.org/jQuery.validator.format
问题:
为什么 jQuery.validation “文档”如此迟钝,甚至严重缺乏基本示例?
真正的问题:
我有一个执行 AJAX 调用的自定义验证器。该调用可以返回需要不同错误消息的各种值。我似乎无法辨别如何根据响应来改变错误消息。一些代码:
<html>
<head>
<script>
// Set error value variable default & scope
var checkEmailErrorMessage = "API Error";
// AJAX Failure Error
checkEmailError = function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 404) {
alert("Could not find the API Server (404)");
} else {
alert("Some horrifying error occurred: " + textStatus);
}
return false;
};
// AJAX Success Handler
checkEmailResponse = function(data, code, jqXHR) {
switch (data.code) {
case 200:
return true;
case 401:
checkEmailErrorMessage = "Duplicate Email";
alert("Sorry, our system has detected that an account with this email address already exists");
break;
case 403:
checkEmailErrorMessage = "Invalid Email";
alert("Sorry, our system has detected that this email is forbidden");
break
case undefined:
alert("An undefined error occurred.");
break;
default:
alert("A horrible error occurred.");
break;
}
return false;
};
// The Custom Validator
jQuery.validator.addMethod("checkEmail", function(value, element) {
$.ajax({
type: "POST",
cache: "false",
async: "false",
url: "/json/checkEmail",
dataType: "json",
data: {
email: function() {
return $("#email").val();
}
},
success: checkEmailResponse,
error: checkEmailError
});
}, checkEmailErrorMessage);
// The Validator Settings
form_validation_settings = {
onkeyup: false,
rules: {
"email": {
required: true,
minlength: 2,
maxlength: 42,
email: true,
checkEmail: true
}
}
};
// The Binding
$(document).ready(function(){
$('#MyForm').validate(form_validation_settings);
});
</script>
</head>
<body>
<!-- the Form -->
<form id="MyForm">
<input type="text" name="email"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
无论如何,错误消息都是“API 错误”。验证文档状态:
消息:可以是由“jQuery.validator.format(value)”创建的函数。
但是我该如何安装呢?我要调用的任何函数都需要是 AJAX 调用的结果。
任何想法表示赞赏。提前致谢!