.net mvc jquery clientside validation problem
i am using .net 4 with mvc 2 and annotations for validation. I built up an own validationAttribute in order to check if an email already exists in my database. The c# function ismailexisting() returns the right value, but the javascript does not act right. The javascript/jquery-part looks like that:
Sys.Mvc.ValidatorRegistry.validators["isexisting"] = function (rule) {
return function (value, context) {
$.ajax({
url: "/persons/ismailexisting",
type: "POST",
data: { email: value },
success: function (data) {
//alert("success: " + data);
if (data == "yes") {
return false;
}
}
})
开发者_开发技巧 return true;
return rule.ErrorMessage;
};
};
If an email already exists, the function ismailexisting() return "yes", otherwise "no". If an email exists (so data is "yes"), the javascript should prevent the user from continueing, because he must enter an other email. If I uncomment the alert(), the value of data is the right one. But somethings keeps the javascript away from providing the right result to my view.
All other stuff for custom validation is realized correctly, because I already implemented a few other custom validations.
Thanks in advance!
The AJAX call, by default, is asynchronous so you can't return a value for the function from the callback. The function has returned the value true long before the AJAX call returns a response. You can get around this by setting async: false
in the options for the AJAX call. Note this will also prevent any other javascript from running on the page while awaiting the response from the server, so use it with caution. Note also that the return in the callback only returns from that function, not the enclosing validator function. Set the value of a captured variable from the outer scope, then return the value of that variable from the validator.
Sys.Mvc.ValidatorRegistry.validators["isexisting"] = function (rule) {
return function (value, context) {
var result = true;
$.ajax({
url: "/persons/ismailexisting",
type: "POST",
async: false, // force the call to run synchronously
cache: false, // we probably don't want to use a cached result
data: { email: value },
success: function (data) {
//alert("success: " + data);
if (data == "yes") {
// set captured value for return
result = false;
}
}
})
return result;
//return rule.ErrorMessage; // you'll never reach this...
};
};
精彩评论