The Techies' pub

Angular 2 – Building Custom Form Validators

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.

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.

1

2

3

4

5

6

7

8

9

10

staticuseruniquecheck(control:Control){

returnnewPromise((resolve)=>{

setTimeout(()=>{

if(control.value=="steve_")

resolve({usernotunique:true});

else

resolve(null);

},2000);

})

}

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.