AngularJS Async validators


Asynchronous validators allows you to validate form information against your backend (using $http).

These kind of validators are needed when you need to access server stored information you can't have on your client for various reasons, such as the users table and other database information.

To use async validators, you access the ng-model of your input and define callback functions for the $asyncValidators property.


The following example checks if a provided name already exists, the backend will return a status that will reject the promise if the name already exists or if it wasn't provided. If the name doesn't exist it will return a resolved promise.

ngModel.$asyncValidators.usernameValidate = function (name) {               
     if (name) {
          return AuthenticationService.checkIfNameExists(name); // returns a promise
     } else {
          return $q.reject("This username is already taken!"); // rejected promise

Now everytime the ng-model of the input is changed, this function will run and return a promise with the result.