I\'m trying to implement a .NET Custom Validator that uses $.ajax to query a WebMethod on the same page and return a boolean value to indicate whether the result is true or
The easy way is by changing your validate to:
function validatePromo(src, args) {
var isValid;
$.ajax({
type: "POST",
url: "Register.aspx/IsPromoValid",
data: "{'code': '" + args + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
isValid = msg.d;
}
});
args.IsValid = isValid;
}
Take special note of the async:false
. The reason your first try didn't work is that the ajax success callback was not getting called until after the validation scripts had already checked args.IsValid. With async:false, the $.ajax call won't complete until after the success callback is done.
The big issue with this is that it now "blocks" whatever js thread is running the validation. In the case of ASP.Net validators, I don't believe this is an issue but I would test it with a long-running call just to make sure you aren't screwing up your page for anyone on a slow connection.