jQuery validator and a custom rule that uses AJAX
For anyone else who stumbles upon this, validate supports 'remote' method, which may not have existed in 2010:
https://jqueryvalidation.org/remote-method/
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}
}
}
});
You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.
You will need to work with async
. See also this post: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Something like:
function myValidator() {
var isSuccess = false;
$.ajax({ url: "",
data: {},
async: false,
success:
function(msg) { isSuccess = msg === "true" ? true : false }
});
return isSuccess;
}
Warning:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().