0

I am trying to create a custom validator for an Angular reactive form that checks for the existence of a username in a Firestore database. The validator is working as expected and returning the expected error object, but I am having trouble displaying the error message in the HTML DOM.

Here's my custom validator class:

export class CustomValidator {
  static username(firestore: Firestore) {
    return async (control: AbstractControl) => {
      const username = control.value;
      const docRef = doc(firestore, 'usernames', username);
      const docSnap = await getDoc(docRef);
      console.log(docSnap.exists());
      return docSnap.exists() ? { usernameTaken: true } : null;
    };
  }
}

my ts file:

import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import {
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
} from '@angular/forms';
import { doc, Firestore, getDoc } from '@angular/fire/firestore';

form!: FormGroup;

constructor(private firestore: Firestore) {}

ngOnInit(): void {
    this.form = this.fb.group({
      username: [
        '',
        [
          CustomValidator.username(this.firestore),
        ],
      ],
    });
}

And here's my template code:

<form [formGroup]="form">
  <input type="text" formControlName="username">
  <div *ngIf="form.get('username').hasError('usernameTaken')">
    <div class="alert alert-danger">
      This username is already taken
    </div>
  </div>
</form>

The problem is that the error message is not displayed in the HTML DOM. Can anyone help me understand what I am doing wrong?

3
  • this looks similar. Can you check if it helps Commented Jan 19, 2023 at 11:10
  • Thanks for the help. Unfortunately, it does not provide enough. Commented Jan 20, 2023 at 10:12
  • can you replicate your issue on https://stackblitz.com. It would be helpful and everyone can try to solve on stackblitz easily. Commented Jan 22, 2023 at 12:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.