How to create a custom async user-exists validator in Angular

Derick Jang
6 min readJul 19, 2021

In Angular, there are two approaches to create forms. One is the template-driven way and the other way is reactive. This post will help you create a custom async validator that checks if a username is available working on the template-driven forms.

Although Angular provides built-in validators such as MinValidator, MaxValidator, EmailValidator, CheckboxRequiredValidator, you will need to create your own validators in many cases such as custom password strength validator, custom password match validator, and custom image url validator.

In this post, I will explain how to create a custom async validator that checks if a username is available, so that we can always have unique usernames.

Basic Setup

To create a custom validator, run the following command in your Terminal:

ng generate directive user-exists

This command will create user-exists.directive.ts as follows:

In your @Directive metadata, add the providers key containing an object that owns provide, useExisting, and multi
properties. NG_ASYNC_VALIDATORS is a token for registering additional asynchronous validators. For useExisting

--

--