Ciel Ciel - 1 year ago 72
jQuery Question

jQuery Validation - difficulty implementing custom validator with $.ajax request

I'm trying to add a custom validator that fetches some information from the server. I am aware of the

validation method, and I don't want to use it because I'm trying to wrap this logic in its own validator... since I need to repeat it in several places, and want
free up for other things.

I'm having a very difficult time with the
nature of it though. Turning
off on
is deprecated now in
jQuery 3.0
, and I can't seem to figure out any other way to get it to hold off on returning the result until the request completes.

(function () {
$.validator.addMethod("customRemote", function (value, element, param) {
url: `/api/url`,
dataType: 'json',
type: 'POST',
data: {id: param, value: value}
}).done(function (response) {
console.log('always executes later ...');
return response;
console.log('always executes first ...');
}, "Error message ...");

The method on my server gets hit and does everything it is supposed to, and it returns the right result. But the validator gets a response before that ever happens. I can't seem to get it to work.

I should add, I'm sending
with the
option set to true, since only an authenticated user can even hit the server.

Answer Source

You can use the remote method source code as base, and implement your customRemote.

Note the return "pending", this is some keyword for internal control of async validations.

remote: function( value, element, param, method ) {
  ...//other code
return "pending";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download