In my Angular/Ionic project, I use an async validator to check for existing usernames stored as fields on user documents in a users collection. In my constructor I have:
this.signupForm = formBuilder.group({
username: ['', Validators.compose([Validators.required,
Validators.minLength(2),
Validators.maxLength(24),
this.asyncValidator.bind(this)],
password: ['', Validators.compose([Validators.minLength(6),
Validators.required])]
})
My asyncValidator method:
asyncValidator(control) {
let username = control.value
return new Promise(resolve => {
this.checkUsername(username).then(snapshot => {
if(snapshot.docs.length > 0){
resolve({
"username taken": true
});
} else {
resolve(null);
}
})
})
}
My query to Firestore:
checkUsername(username) {
return firebase.firestore().collection('users').where("username", "==", username).get()
}