Angular 5 – Async validation with Firestore

Hi Friends,

Hope you are all well. This is one of the most requested posts in this site. This post deals with how to write some simple custom validators and validate inputs on our form fields.

Let’s begin.

A screencast of this post.

The code for this post is available – here.

What we’ll be doing:

This is going to be a simple demo without any styling or anything. I’ll create two input fields one for email and another for a nick name. Once the email is done and the user moves to fill in the next field, the input entered in the email field is checked with the users in the system. If it’s already present a message is shown, if not it’s valid.

Alright, let’s start.

Scaffold out an application using the angular-cli and then install firebase and angularfire2 using the below commands.

Now open up the project in your favourite editor and add the firebase configuration to your environment/environment.ts file as shown below.

Now open up app.module.ts file and import all the modules that we’ll be using  in our app. Your final app.module.ts file would look like this.

Now open up app.component.html file and add the below code.

The focusout attribute is the one that triggers the emailcheck funtion when the input field loses focuses i.e., when the user moves on to the next input field.

The status will show a message when the email check is done. Now let’s wire up this html to code in the app.component.ts.

Before opening up the app.component.ts open up your firestore instance and add a collection called users. Now in this collection add a document that has a field called email as shown below.

first

Open up app.component.ts and add the below code.

The above code is pretty much self-explanatory I guess. We are simply constructing a query where we check if the email is already present in the users collection. If it’s there then we show a message accordingly.

Now run the app. Type an email that exists in your collection, move on to the next input field and watch the message that get’s displayed. Now type an email that’s not in your collection and move to the next field and watch what happens.

That’s how you make a simple custom async validator guys. I hope this was helpful to you. If this helped you kindly share it with someone and help them too. Donate to keep this site alive.

Thanks for reading. Peace.. :)

Liked it? Take a second to support admin on Patreon!
  • romain

    can you do the same creating a formGroup programmatically and adding an asyncValidator?

    • I don’t understand.. formGroup programmatically..? You mean with a structural directive..?