Angular 2 – Building Custom Form Validators

Hello Friends,

Hope you are all well. This tutorial deals with building custom validators for your form fields. Forms are the most used UI components in several apps as they provide an excellent way of receiving input from users.

To make sure you don’t receive junk data and to guide the user to enter correct values in a field you need to make sure that you provide some validation in the form fields to simplify the whole data checking process.

Let’s begin

The code used in the tutorial is available here.

A video screencast of the tutorial


Now the validators in Angular 2 can be classified as follows

  • Built-in Validators
  • Custom Validators
  • Asynchronous Validators

Before diving into these and how they can be used we will look at few other components that can be used for playing with form fields in Angular 2.

Controls and Control Groups:

A Control is simply like a variable that could be bound to input elements. Controls can have values. They can take in 3 arguments i.e, An input value, Validators and Async Validators.

Control Groups are nothing but a group of controls or a part of form. The FormBuilder class could be used to represent control groups in Angular 2.

We will learn the three types of validators using a small example.

Get the angular 2 seed repo from here

We will install the bootstrap-material-design to add some beauty to our form. Go ahead and install it using the below command.

Once you install it open up index.html and make sure to add the references as shown below (in the head section).

Now create a new file in the app directory called form.html and add the below code.

Let me explain what I have done in this form along with the ts code. Open up app.component.ts file and add the below code.

  1. Now I have a control group called form which I have bound to the form in the form.html using [ngFormModel].
  2. I have two controls username and password which I have bound to the form using ngControl.
  3. #username and #password are just two local references which I use to check for errors and display messages accordingly.

Now if you see in the above code we have used the Built in Validator ‘required’.

There are just three Built in Validators namely:

  • Required
  • maxLength
  • minLength

As you could guess the maxLength and minLength are used to limit the number of characters of input a field could take.

Now let’s move on to custom validators.

Suppose you want to write a validator that checks whether the username field has an underscore and if it doesn’t prompts the user to add one.

Well, follow the below steps to get one.

Open a new file called customvalidator.ts in app directory and add the below code.

I am just checking whether the input field has an underscore by referencing the control here.

Open up app.component.ts file and modify it so that it looks like below. (Don’t forget to import customvalidator class.)

Here as you can see I am using Validators.compose to use two validators for a single control. Open up form.html and add a new error message for this validator as shown below.

This is along with the previously added error message for required validator.

Now you could see that the form expects a username and expects the username to have an underscore, if validation fails it throws up an error message accordingly.

Let’s move on to the next part, i.e., Async Validators.

Asynchronous validators are the ones that make calls to a server to process our data and return a response accordingly. For eg., checking the uniqueness of a username. Let’s do the same in our app.

Open up customvalidator and add the below function as well.

As you could see I have used a promise here mainly to illustrate my point. Server calls usually return promises which are then resolved according to the server response.

Here I have simple added a condition to check whether the given username matches steve_ (Remember, we used the underscore validator as well). I have written this inside a timeout function (with 2 seconds) so as to simulate a server call.

Now open up app.component.ts and modify it as shown below.

Note that I have added the Async Validator as a third argument to the username control.

Open up form.html and add an error message for this validator as well.

The final form.html would look like this.

I have added a few lines of code to put our form in a panel so that it looks more elegant.

Now you could use any username (with an underscore) except steve_.

This is how form fields are validated in Angular 2.

The same procedure could be used to created validators in Ionic 2 or any other framework built with Angular 2 as the base.

Thanks for reading guys. Peace.. :)