Fireship · @fireship
Async Validation with Angular Reactive Forms + Firebase
Uploaded February 14, 2018 · Length 7:20
Summary
build custom async validator for unique username in angular reactive forms with firebase
- angular reactive forms
- firebase validation
- async validator
- username uniqueness
- custom validator
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
Angular Reactive Forms have a useful set of built-in validators, but it's not so obvious
- 0:07
how you would validate something like username uniqueness when those usernames are saved in
- 0:11
an external database such as Firebase. For something like that, you're going to need
- 0:15
to build your own custom asynchronous validator, and that's exactly what I'm going to show
- 0:19
you today. The validator is going to see if we have any users with a specific username
- 0:24
in the Firestore database, and if so, it's going to trigger a reactive validation error,
- 0:29
which we can respond to in the front end.
- 0:31
First make sure to like and subscribe and grab the source code from angularfirebase.com
- 0:36
because you'll be able to use this validator throughout your reactive forms.
- 0:39
We'll get started from a brand new Angular 5 app and I've installed Angular Fire 2 so
- 0:44
follow the install instructions on the official repo.
- 0:47
I've also created a basic sign-in component which is in the declarations and then we're
- 0:51
importing the reactive forms module in the import section in addition to our Angular
- 0:56
Fire dependencies.
- 0:57
In this demo I'm making the assumption that you have some custom user data saved in the
- 1:01
database, but the validator can work with any type of asynchronous data, whether it's
- 1:05
from Firebase or some other source.
- 1:08
If you're brand new to Firestore Auth, I recommend starting out with episode 55.
- 1:12
The end result of that lesson is a collection of users in the Firestore database.
- 1:17
Each user document has some custom user information saved about them.
- 1:20
In this case we have a username, and we want to validate that every new user has a unique
- 1:24
username when they sign up.
- 1:26
So the first thing we need to do is build out to reactive form to collect the user information.
- 1:32
Inside of our component, we import Angular Firestore as well as our reactive form classes.
- 1:37
Then we can inject Angular Firestore and FormBuilder in the constructor.
- 1:42
Then to build out a reactive form all we have to do is declare it as a property and then call formBuilder group along with our actual form control fields We go ahead and give it a form field for email The first value here is just an empty string which defines the default value
- 1:57
Then we can pass it some default validators that we get from Angular.


