ngModel.NgModelController.$asyncValidators

$asyncValidators

Object.<string, function>

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. When the asynchronous validators are triggered, each of the validators will run in parallel and the model value will only be updated once all validators have been fulfilled. As long as an asynchronous validator is unfulfilled, its key will be added to the controllers $pending property. Also, all asynchronous validators will only run once all synchronous validators have passed.

Please note that if $http is used then it is important that the server returns a success HTTP response code in order to fulfill the validation and a status level of 4xx in order to reject the validation.

ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  var value = modelValue || viewValue;

  // Lookup user by username
  return $http.get('/api/users/' + value).
     then(function resolved() {
       //username exists, this means validation fails
       return $q.reject('exists');
     }, function rejected() {
       //username does not exist, therefore this validation passes
       return true;
     });
};
doc_AngularJS
2016-03-29 16:12:14
Comments
Leave a Comment

Please login to continue.