I'm struggling with some validation using jQuery's validator plugin.
Basically I'm checking if username already exists, so I used addMethod to create my own method. I post a request via AJAX to a controller (controller as in MVC pattern) that queries the database and generate a response telling if username exist or not. Here's the code:
$.validator.addMethod("username_available", function(value, element) {
$.ajax({
url: MyPostURL,
type: "POST",
dataType: "html",
data: ({username: jQuery.trim($("#username").val()),
}),
success开发者_运维百科: function(data) {
if (data == "True")
return true; // Available
else
return false; // Already exists, not available
}
})
}, "Username not available.");
No matter if is the field is available, the error message "Username not available." keeps displaying.
The response from MyPostURL is O.K. I did some debugging placing some alerts() and the results made sense. I made sure that the controller is echoing instead of returning.
As far as I can tell, the logic in the method seems O.K., so I must be missing something.
Anyone could shed some light on this?
T.I.A.
Your $.ajax
call is asynchronous so your validator returns before the AJAX call is complete; the return
statement inside your success handler isn't returning a value from your validator, it is only return a value from the success handler and no one cares what your success handler returns. Your validator callback function doesn't return any value at all and that lack of a value is interpreted as "false" by the validator engine.
You could make the $.ajax
synchronous:
$.validator.addMethod("username_available", function(value, element) {
var is_valid = false;
$.ajax({
// as before...
async: false,
success: function(data) {
is_valid = data == 'True';
}
});
return is_valid;
}, "Username not available.");
But that will lock up the browser until the $.ajax
call completes. That's probably okay for a simple "username is available" validation though.
精彩评论