jQuery validator addMethod, no matter what displays error message

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) {
        url: MyPostURL,
        type: "POST",
        dataType: "html",
        data: ({username: jQuery.trim($("#username").val()),
        success: function(data) {
            if (data == "True")
                return true; // Available
                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?



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;
        // 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.

Need Your Help

Toggling AirPlane mode in iOS Programmatically

ios iphone frameworks iphone-privateapi airplane

I want to on/off airplane mode in iOS programmatically. After googling, i got some of the following links, and followed them,

Parent-child dimension - confused levels

mdx olap ssas-2008

I am running Analysis Services 2008 R2 and have come across some behavior that I really do not understand and I can't seem to get to the bottom of it. I have a dimension called Segment which is a s...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.