Angular validate mail using behavior subject with focus out

Viewed 31

Am passing valid emails from the component to the service.ts file to make third-party API calls to validate it. Here the problem is I changed the existing method to a focus-out method the service method is not returning any responses.Below is the existing method i wants to change it using focus out method:

<input
              class="form-control"
              type="text"
              tabindex="0"
              id="address_email"
              name="address_email"
              autocomplete="email"
              placeholder="{{ 'addressForm.email.placeholder' | cxTranslate: { context: isoCode } }}"
              formControlName="email"
              (focusout)=validateEmail();
            
            />

email$: BehaviorSubject<string> = new BehaviorSubject(undefined);
 emailControl = new addressFormControl(
    '',
    [Validators.required, Validators.email],
    [this.emailValidator.isValid(this.email$)]

); service.ts

 isValid(email$: Observable<string>, isWarning = true): any {
    return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
      const allowList = ['Valid', 'Valid_CatchAll'];
      return combineLatest([email$, timer(300)]).pipe(
        switchMap(([email]) => {
          if (this.checkIfEmailInString(email)) {
            return this.httpClient
              .get('https:url, {
                params: {
                  Key: 'adfadsfadsfasdf',
                  Email: control.value,
                },
              })
              .pipe(
                map((resp: any) => {
                  const responseItem = resp?.Items[0];
                  if (!responseItem) {
                    return {};
                  }
                  const formValidationErrors = !allowList.includes(responseItem.ResponseCode)
                    ? { invalidEmail: true }
                    : {};
                  if (isWarning && control instanceof SnFormControl) {
                    control.setWarning(formValidationErrors);
                  }
                  return formValidationErrors;
                }),
                take(1)
              );
          } else {
            return of([]);
          }
        }),
        take(1)
      );
    };
  }
  private checkIfEmailInString(text): boolean {
    const re =
      /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/;
    return re.test(text);
  }
}

so kindly help me out to make API calls once the user enters the valid email.Thanks in advance.

0 Answers
Related