Exploring the implementation of a custom validator within an Angular service

I have been attempting to implement a custom validator to validate if an email is already in use. After consulting the documentation and reading various articles, I have come up with the following code:

In my auth.service.ts file

checkEmail(email) {
    const r$ = of(true);
    const x$ = of(false);
    return this.http.post<any>(`${config.apiUrl}/users/email`, email)
    .pipe(
      mergeMap(v =>
        iif(
          () => v,
          r$,
          x$
        )
      )
    );
  }

In my component

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.email,
        this.checkEmail.bind(this)
      ]]
    });
  }



checkEmail(control: AbstractControl) {
    if (control.value) {
      return this.authService.checkEmail({email: control.value}).toPromise()
      .then(response => {
        return response ? { forbiddenName: {value: control.value}} : null;
        });
    }
  }

Despite my efforts, it seems that the checkEmail() function is not returning the correct data for the validator's validation. How can I rectify this issue?

Answer №1

you must have these mods installed:

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.email
      ], [this.checkEmail.bind(this)]] // async validators go separate after sync validators
    });
  }



  checkEmail(control: AbstractControl) {
    if (control.value) {
      return this.authService.checkEmail({email: control.value}).pipe(
        map(response => {
          return response ? { forbiddenName: {value: control.value}} : null;
         }) // use observables, don't convert to promises
       );
    }
    return of(null); // gotta return an observable for async
  }

this part is not mandatory but can make things easier / more organized:

  checkEmail(email) {
    return this.http.post<any>(`${config.apiUrl}/users/email`, email)
    .pipe(
      map(v => !!v) // map and coerce to bool
    );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

Discover the steps to include the property within the data model in Angular specifically meant for showcasing on the user interface list page

class UserIdentity { public uniqueID: string; public fullName: string; public bio: string; public service: string; public groupID: string; public userID: string; public secretKey: string; constructor(details?: any) { this.uniqueID = &a ...

Filtering data on objects in Angular can be achieved by utilizing the built-in

Retrieving data from the backend using this function: private fetchData(): void { this.dataService.fetchData().pipe( tap((response: any) => { this.persons = response.results; this.familyMembersTrue = this.persons.filter(x =&g ...

Improving Your Utilization of Angular's @input() Feature

My current dilemma involves a sub-component that requires three variables from the parent component. These three variables all stem from one object, like so: let man = {name:'John',gender:'male',age:42,birthday:'1976-6-12'} ...

Modifying the dimensions of mat-card in Angular Material

https://i.stack.imgur.com/CP16N.png I am struggling to make both components the same height, similar to the left form. I have tried adjusting margins and padding but nothing seems to work. Below is the HTML code for the parent element: <mat-tab label= ...

Utilize variable as both a function and an instance of a class

Is there a way to access a variable as both a function and an object instance using TypeScript? log("something"); log.info("something"); I've attempted various methods, such as modifying the prototype, but nothing has proven succ ...

How to create an Ion-select element with dynamic options in Ionic 2?

Currently, I am working on an application in Ionic 2 and I am facing a challenge with adding ion-select options dynamically. Below is the snippet of my code: <ion-select [(ngModel)]="classifications" (ngModelChange)="updateSelectedValue($event)"> & ...

Developing Custom Methods with TypeScript Factories - Step 2

Working in a factory setting, I find myself needing to incorporate custom methods at some point. Thanks to the valuable input from the community, I've made progress towards my goal with this helpful answer, although I'm required to include a see ...

Error: The TranslateService provider is not found and needs to be added to the

When attempting to make translation dynamic in angular2 using the ng2-translation package, I encountered an error message: Unhandled Promise rejection: No provider for TranslateService! zone.js:388Unhandled Promise rejection: No provider for TranslateSe ...

Is it impossible to extend a Typescript class with an overriding method that uses a different parameter?

I am currently working on a Typescript MVC app and encountering an issue. When I try to extend my BaseController and override the ajaxMethod with different parameters, my transpiler throws an error. Any help would be appreciated. Below is the code snippet ...

Validation errors in the realm of Zod

Below is my code using Next.js 14 with TypeScript, React Hook Form, and Zod for validation. The issue arises when trying to display an error message for an empty form: import React from "react"; import category from "@/components/expenses/ca ...

Angular 2: Utilize the select event to fetch and return the selected item

How can I pass an item on change event? Currently, my code looks like this: <select #sel (change)="select.emit(sel.value.url)"> <option *ngFor="let item of selectlist"> {{item.description}} </option> &l ...

Error: Unrecognized action type in Vuex

I've been encountering some major issues with vuex lately. For some reason, getters, actions, and mutations are not being recognized. In the code snippet below, although fetchFacilities is working fine, addFacility is throwing an error: [vuex] unknown ...

Creating a JavaScript library with TypeScript and Laravel Mix in Laravel

I have a Typescript function that I've developed and would like to package it as a library. To transpile the .ts files into .js files, I am using Laravel Mix and babel ts loader. However, despite finding the file, I am unable to use the functions: ...

Angular: Guidelines for detecting checkbox change events and dynamically updating content in a separate component

One of my components contains a checkbox element: <mat-checkbox class="mr-5"></mat-checkbox>. I want to be able to detect when this checkbox is checked or unchecked, and based on its state, display text in a separate component that is ...

Listening for events from an Angular 4 component within an AngularJS controller

Currently, I am in the process of developing a hybrid angular application. One specific requirement I have is to monitor an event (potentially an observable) within the angularjs controller that would be initiated by an angular 4 component. Are there any ...

Utilizing Typeface Styles in SCSS with the Latest Webpack Version 4

My Angular 6 SPA utilizes Webpack 4 for bundling, and I have encountered an issue while trying to import external fonts into the project. The project is based on the repository found at; AngularWebpackVisualStudio Example Repo After inspecting the webpac ...

Encountering an unexpected closing tag "a" while using Angular 2 with webpack

I am currently working with an Angular 2 template that displays tabs on my website: <div id="menu"> <ul id="tabs"> <li *ngFor="let tab of tabs; let i = index" [class.active]="selectedTab===i"> <a routerLink="/p ...