Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery validation plugin remote query - error/failure handling

I'm using the jquery validation plugin on a user profile editing form. I'm using the 'remote' feature to query my website and check email uniqueness, which is working well. My question is about how to deal with errors or failures, which doesn't seem to be well documented. The behaviour I want is that if the JSON query fails or times out forget this part of the validation, allow the user to submit and let the server side validation take care of it.

I can see there is an error attribute, and it looks like you can add a function to run in that scenario, but what would I put there to switch off the validation rule in case of timeout/error/failure?

remote: {
                url: location.pathname + "/EmailUnique",
                timeout: 20000,
                data: {
                    userID: function() {
                        return $("#Form_EditProfileForm_userID").val();
                    }
                }
            }
like image 520
user1181064 Avatar asked Oct 08 '22 20:10

user1181064


1 Answers

Yes, add an error function:

remote: {
    //your normal $.ajax stuff here
    ,
    error: function(jqXHR, textStatus, errorThrown) {
       //deal with the error
    }
}

All of these parameters are passed to a normal jQuery ajax call, so by specifying an error function, you get to handle whatever happens.

Assuming you've saved your validation object in a variable v, your error function could be this simple:

$('#inputWithRemote').rules('remove','remote');.
v.pendingRequest--;

Honestly, the v.pendingRequest business is to deal with what I would call a bug in the Validation plugin - it increments this pendingRequest counter when it kicks off the ajax request, but doesn't have it's own code to deal with errors in the response.

See it in action here: http://jsfiddle.net/ryleyb/H96TD/ (note that I've set the timeout to 2 seconds and used some of jsfiddle's special ajax code to force the response to take 3 seconds).

like image 109
Ryley Avatar answered Oct 12 '22 10:10

Ryley