jQuery, custom validations, and AJAX
My question is more process based than code based, but to share (and maybe stumble upon some inconsistencies) I am using:
- jQuery 1.6.2
- jQuery Validations 1.8.1
So here goes...
When adding in a custom validation (using addMethod) that requires a call to the server (instead of the remote call built in), you must set to response to happen synchronously because the method will finish before the result returns from the server. Is this correct?
I'm also assuming the 2 main ways to do this are via calling开发者_开发知识库 an $.ajax request with async false, or deferred.promise(). Is this correct?
I've been looking thru many posts that ask questions related to custom validation using getJSON and the responses are usually "you're not returning anything back" but doesn't this miss the point - isn't the response too late as well?
Thanks for any responses!
Your assumptions are correct. You cannot use asynchronous requests with custom methods because the jQuery validate needs to know that this is an async request. That's why you should use the remote
rule in this situation and not custom methods:
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}
}
}
});
Synchronous AJAX requests (or SJAX) are not something that I would recommend you doing.
精彩评论