1

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.

Ciel
  • 4,290
  • 8
  • 51
  • 110
  • If the validator requires being synchronous, you can't fix this without using *very* poor practices or modifying the validator. – Kevin B Aug 10 '16 at 17:41
  • This may be of interest to you. https://jqueryvalidation.org/remote-method/ – Kevin B Aug 10 '16 at 17:46
  • You can use the remote method code (https://github.com/jzaefferer/jquery-validation/blob/master/src/core.js) as base, and implement your customRemote. – Douglas Fernandes Aug 10 '16 at 18:26
  • Note the return "pending", this may be some keyword for internal control of async validations. – Douglas Fernandes Aug 10 '16 at 18:34
  • @DouglasFernandes can you post that as the official answer so I may award credit? That ended up being the solution. – Ciel Sep 01 '16 at 10:12
  • @kevin-b maked this question as an duplicate, i can't post an new answer. – Douglas Fernandes Sep 01 '16 at 15:25
  • Except it's not a duplicate. The problem specific to jQuery Validation had to do with specific implementation of an asynchronous call - it's a completely different question. – Ciel Sep 01 '16 at 15:41

1 Answers1

0

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";
}