I m new to Angular. I have configured project with FireStore. Everything is working fine. Now I want to register only those users who don't have account with us and give error message to those who are already registered.
Here is register.component.ts
this.form = this.fb.group({
firstName: new FormControl('',[
Validators.required,
Validators.minLength(3)
]),
lastName: new FormControl('',[
Validators.required,
Validators.minLength(3)
]),
email: new FormControl('',[
Validators.required,
Validators.email,
CustomValidators.shouldBeUnique(this.afs)
])
});
And here is Custom Validator ShouldBeUnique(afs) method.
static shouldBeUnique(afs: AngularFirestore): ValidationErrors | null{
let emailExists: boolean;
return (control: AbstractControl) => {
let emailVal = ''
let email = control.get('email').value;
let collref = afs.collection('users').ref;
let queryref = collref.where('email', '==', email);
queryref.get().then((snapShot) => {
if (snapShot.empty) {
// this.status = 'valid';
console.log('Email is avalible.');
return null;
}
else {
console.log('Email is already registered.');
return { shouldBeUnique: true };
}
});
}
}
Code is working fine and returning null if email is not in DB. But problem with the code is when email exists in DB it only prints message in console and not returning { shouldBeUnique: true };.
Any sort of help will be appreciated.