2

I'm trying to do an async validation to an email input to check if exists. My directive looks like this:

app.directive('emailExist', ['$http', function ($http) {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {
        ctrl.$asyncValidators.emailExist = function (modelValue) {
            return $http({
                method: 'POST',
                url: '\email-existance',
                data: {
                    email: modelValue
                }
            }).then(function(res) {
                console.log(res)
                return (res === 'exist') ? false : true ;
            });
        }
    }
};
}]);

So as far as I understand, asyncvalidators should return true or false based on the validation. (or is it just the sync validators - and if so, what does the async returns? )

Server works and returns me true or false for existance but in both cases my validation stays valid (even when it detects that the email exist)

Please help me!

1 Answer 1

4

An $asyncValidator should not return true/false. It needs to return a rejected or resolved promise.

A collection of validations that are expected to perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided is expected to return a promise when it is run during the model validation process. Once the promise is delivered then the validation status will be set to true when fulfilled and false when rejected.

docs

So what you would do is:

return $http.get('...')
            .then(/** resolve **/)
            .catch(/** reject **/);

Or, if your backend is only serving you 2xx statuses (some SPA apps require this to be true in some cases), I would check the data of said response in your then handler and handle resolve/reject on a deferred object a la $q.defer().

Such as:

var deferred = $q.defer();

$http.get('...').then(function (res) {
  res.someCondition ? deferred.resolve('yay!') : deferred.reject('boo!');
});

return deferred.promise;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.