Reputation: 2610
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!
Upvotes: 2
Views: 364
Reputation:
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.
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;
Upvotes: 4