简体   繁体   中英

Angular Firestore Unique name validation (Reactive Forms)

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.

Your problem is here:

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 };
        }
    });

You are trying to use the return inside the then function but that is a async execution and your code will not wait for that to finish. This is why the console.log is working but the return statement is not.

I suggest you use the async/await approach to reduce complexity and let me know if I can help you any further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM