I'm trying to add a custom validator that fetches some information from the server. I am aware of the remote
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 remote
free up for other things.
I'm having a very difficult time with the async
nature of it though. Turning async
off on $.ajax
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) {
$.ajax({
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 XHR
with the credentials
option set to true, since only an authenticated user can even hit the server.