Useful references:
- jQuery validation: change default error message
- http://jqueryvalidation.org/jQuery.validator.addMethod
- http://jqueryvalidation.org/jQuery.validator.format
The question:
Why is the jQuery.validation "documentation" so obtuse, with a serious lack of even basic examples?
The real question:
I have a custom validator that does an AJAX call. That call can return various values which will require different error messages. I can't seem to discern how to get the error message to be varied based on the responses. Some code:
<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>
No matter what, the error message is "API Error". The Validation docs state:
messages: Can be a function created by "jQuery.validator.format(value)".
But how would I rig this up? Any functions I would call would need to be results of the AJAX call.
Any ideas are appreciated. Thanks in advance!