How To Write an Async Validator In AngularJS
Today let's learn about async validators in AngularJS and how you can use it in your projects.
Brief background
We want to check if a username exists or not every time a guest enters the username in the input field. In this tutorial, I will show an error if the server already has that username.
Let's begin:
First, let's create a simple form with username and password input fields.
<form name="myForm" ng-submit="vm.submit()">
<label>
Username:
<input type="text" name="username" ng-model="vm.signupForm.model.username" required>
</label>
<label>Password: </label>
<input type="password" name="password" ng-model="vm.signupForm.model.password" required>
<button type="submit" ng-disabled="myForm.$invalid">Sign Up</button>
</form>
Next, let's write a directive name called usernameExist
angular.module('test').directive('userExist', function($http, $q) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.userExist = function(modelValue, viewValue) {
return $http.post('/username', {username: viewValue})
.then(
function(response) {
if (!response.data.status) {
return $q.reject();
//Server will give me a notify if it exist or not. I will throw a error If it exist with "reject"
}
return true;
}
);
};
}
};
});
Before we proceed with the next steps, we need to fix something on the form.
- First, use directive on the input
<input type="text" ng-model="vm.signupForm.model.username" required user-exist >
- Next, change the condition on the submit button (To ensure that when the async validation tries to connect with $http, it will disable this button).
<button type="submit" ng-disabled="myForm.$invalid || myForm.$pending">Sign Up</button>
Wrapping up
That's it! It's that simple!
To learn more about AngularJS, you can check out other tutorials like: AngularJS Directives: A Beginner’s Practical Guide, Angular Form Validation - ngModelController, and Migrating from Angular 1.x to Angular 2: Upgrade Strategies.