0

In my current application I am trying to build a form that allows users to change their email or username. I have a validator on the form fields so users cannot have the same username or password as other users. I prefill the field with users' current username and email, however, if I click into that field delete one character and then reapply it, I trigger warning text. How can I make the validator not raise an error if the current user enters their own username?

import { Injectable } from '@angular/core';
import { FormControl, AbstractControl } from '@angular/forms';
import { UserinfoService } from 'src/services&Validtors/userinfo.service';
import { map } from 'rxjs/operators';
import { HttpClient, HttpParams } from '@angular/common/http';


@Injectable()
export class EmailValidator {
    constructor(private http:HttpClient) { }


    validateEmailNotTaken(control: AbstractControl) {
        return this.checkEmailNotTaken(control.value).pipe(
          map(res => {
            return res ? null : { emailTaken: true };
          })
        );
      }
    
      
      checkEmailNotTaken(email: string) {
        return this.http.get("http://127.0.0.1:8000/accounts/UserDataEmail/").pipe(
          map((emailList: Array<any>) =>
            emailList.filter(user => user.email === email)
          ),
          map(email => !email.length)
        );
      }




}

1 Answers1

0

You need to implement AsyncValidator:

import {AbstractControl, AsyncValidator, ValidationErrors} from "@angular/forms";
import {Injectable} from "@angular/core";
import {Observable, of} from "rxjs";
import {catchError, map} from "rxjs/operators";

@Injectable({ providedIn: 'root' })
export class EmailValidator implements AsyncValidator {

  constructor(private emailService: YourEmailService) {}

  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return this.emailService.isEmailTaken(control.value).pipe(
      map(isTaken => (isTaken ? { emailTaken: true } : null)),
      catchError(() => of(null))
    );
  }
}

I strongly recommend you to create the checkEmailTaken in a Service as shown above, that returns a Observable<boolean>

For further details, check "Implementing a custom async validator" in the Angular documentation.

Santi Barbat
  • 2,097
  • 2
  • 21
  • 26