views:

24

answers:

1

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?

+2  A: 

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:

$("form").validate({
  rules: {
    username: {
      remote: {
        url: "http://" + location.host + "/scripts/ajax/check_username.php",
        type: "post"
      }
    }
  }  
});

This will POST a username: valueofElement since the rule is for the element named username. Your server-side script should return true if the validation should pass, false otherwise...so false if the user name is already taken.

You can read more about the remote option here, including how to pass additional data arguments if needed.

Nick Craver
woot woot, you're the man :D
Aaron Hathaway