I really was trying to avoid asking this question. I have seen quite a few posts on SO regarding this plugin but they still didn’t quite get it for me. Right now I have a new account registration form and I’m trying to write a custom method for validating a unique username. I would like to think that the following should work:
$.validator.addMethod(
"uniqueUsername",
function(value, element) {
$.post(
"http://" + location.host + "/scripts/ajax/check_username.php",
{
username: value
},
function(response) {
if(response == 'true') {
return true;
} else {
return false;
}
}
);
},
"This username is already taken."
);
Unfortunately it seems like the plugin moves on regardless of the callback function. I found someone suggest doing something like the following:
var result = false;
$.validator.addMethod(
"uniqueUsername",
function(value, element) {
$.post(
"http://" + location.host + "/scripts/ajax/check_username.php",
{
username: value
},
function(response) {
if(response == 'true') {
result = true;
} else {
result = false;
}
}
);
return result;
},
"This username is already taken."
);
But it seems to have a delay since it stores the value, then on the next event will set whatever the value is. What do you guys recommend?
Since this is an asynchronous check, there needs to be more around it (you can’t return a value from a function like this, it’ll always be false in your case). The built-in method is
remote, used like this:This will POST a
username: valueofElementsince the rule is for the element namedusername. Your server-side script should returntrueif the validation should pass,falseotherwise…sofalseif the user name is already taken.You can read more about the
remoteoption here, including how to pass additional data arguments if needed.