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();
}
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With