What are the steps to utilize a personalized validation access form within a component?

I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly.

Here is my template:

<form class="forms-sample" #f="ngForm" (ngSubmit)="onSaveUser(f.value)">
  <input type="email" class="form-control" id="email" ngModel name="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" #email="ngModel" placeholder="Email" emailValidator>
  <div *ngIf="email?.errors.emailValidator">This email has been taken, please use another one.</div>
  .......................................................
  <button class="btn btn-md-12 btn-outline-primary btn-fw btn-icon-text clickable" [disabled]="f.invalid || userFile==null" type="submit">
</form>

This is my custom validator:

import { NG_VALIDATORS, FormControl, ValidatorFn, Validator } from '@angular/forms';
import { Directive } from '@angular/core';
import {UsersService} from '../../services/users.service';

@Directive({
  selector: '[emailValidator][ngModel]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: EmailValidator,
      multi: true
    }
  ]
})
export class EmailValidator implements Validator {

  validator: ValidatorFn;

  constructor(public usersService:UsersService) {
    this.validator = this.emailValidator("");
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

  emailValidator(email:string): ValidatorFn {
    return (c: FormControl) => {
      this.usersService.checkEmailTaken(email)
        .subscribe((res)=>{
          let isValid = res;
          if (isValid==null) {
            return true;
          }
        });
      return {
        emailValidator: {
          valid: false
        }
      };
    }
  }

}

My service returns the user data if it exists or null if it does not:

checkEmailTaken(email: string) {
    if(this.jwtToken==null) this.authenticationService.loadToken();
    return this.http.get(this.host+"/checkEmailTaken?email="+email
      , {headers:new HttpHeaders({'Authorization':this.jwtToken})}
    );
}

The service functions properly, but I am unable to determine why my custom validation is not working as expected. Any insights?

Answer №1

Service

fetchUserByEmail(email:string){
    if(this.token==null) this.token = this.authentication.fetchToken();
    return this.http.get(this.host+"/userByEmail?email="+email
      , {headers:new HttpHeaders({'Authorization':this.token})}
    );
}

Validator

import { Directive } from '@angular/core';
import { AsyncValidator, AbstractControl, ValidationErrors, NG_ASYNC_VALIDATORS, AsyncValidatorFn } from '@angular/forms';
import { map } from 'rxjs/operators';
import {UsersService} from '../../services/users.service';


export function validateUniqueUserEmail(usersService: UsersService): AsyncValidatorFn {
  return (c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
    return usersService.fetchUserByEmail(c.value)
      .map(data=> {
        return data ? { 'uniqueUserEmail': true } : null;
      });
  };
}

@Directive({
  selector : '[validateUniqueUserEmail][ngModel]',
  providers : [{ provide: NG_ASYNC_VALIDATORS, useExisting:ValidateUniqueUserEmail, multi:true}]
})
export class ValidateUniqueUserEmail implements AsyncValidator {

  constructor(private usersService: UsersService) {}

  validate(c: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return validateUniqueUserEmail(this.usersService)(c);
  }
}

app.module.ts we need to include the validator in our declarations to utilize it for forms

@NgModule({
  declarations: [ValidateUniqueUserEmail]
})

Template

<input type="email" class="form-control" id="email" ngModel name="email" required validateUniqueUserEmail pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" #email="ngModel" placeholder="Email">
<div *ngIf="email?.errors.uniqueUserEmail">This email is already in use, please enter a different one.</div>

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

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Error encountered during Angular boot process due to npm running lifecycle script ELIFECYCLE

I encountered an issue while trying to boot up my Angular project. I attempted to install necessary plugins, but ran into some errors. { "name": "portal-app", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng ser ...

Performing a Protractor test on an Angular 5 application

We're in the process of transitioning our ui-library from AngularJS to Angular 5. I'm encountering challenges with the protractor tests. I need guidance on how to update the old AngularJS test to align it with Angular 5. If anyone has dealt wit ...

"Using Angular and TypeScript to dynamically show or hide tabs based on the selected language on a website

When switching the language on the website, I want to display or hide a specific tab. If the language is set to German, then show the tab; if any other language is selected, hide it. Here's my code: ngOnInit(): void { this.translate.onLangChange.s ...

Is it possible to utilize the NX CLI for managing both Angular and React applications within the same Nx workspace?

When attempting to set up my workspace, I encountered some errors. To start, I created an Nx workspace by running: npx create-nx-workspace@latest myworkspace, and then chose Angular CLI as the option. Next, I generated an Angular app using the command: y ...

Guide on invoking an HTML event method from a parent component to a child component

I have the following parent component: JS import { Component, OnInit } from '@angular/core'; import { TaskService } from '../task.service'; import { ViewChild } from '@angular/core/src/metadata/di'; import { CreateNewTaskCom ...

``Can you provide guidance on excluding matching values from a dictionary object in a Angular project?

I've developed a function that takes a dictionary object and matches an array as shown below: const dict = { CheckAStatus: "PASS", CheckAHeading: "", CheckADetail: "", CheckBStatus: "FAIL", CheckBHeading: "Heading1", CheckCStatus: "FAIL", ...

Angular does not receive events from Socket.io

Recently I started coding with AngularJS and decided to build a real-time app using Socket.io: The service I'm using shows that the connection is fine on the console. Here's a picture of the Console.log output However, when I attempt to emit c ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Can HTML tag attributes be accessed in CSS within the Shadow-DOM?

As I work on developing a custom component using StencilJS, I find myself needing to adjust the outline behavior when users navigate through it with either a keyboard or mouse. My component employs ShadowDOM and I aim to extract an HTML tag attribute from ...

Specific TypeScript function that exclusively accepts types such as `number|undefined` and does not simply accept `number` alone

I've been working on creating a utility class that can help me throw an exception when something may be undefined, like throwIfUndefined(array[index]).function() and throwIfUndefined(obj.key).function(). My goal is to streamline my code as using if co ...

What steps are needed to have typescript recognize a typed function as a throw-statement?

I'm grappling with a typescript issue - I have a custom function that consistently throws an error, which is used to handle null variables. Strangely, if I directly throw an error without using the function, typescript recognizes that the variable can ...

Oops! The mighty gulp-clean frowns upon attempts to eradicate files outside its domain

Whenever I execute the command: gulp clean I encounter an error even though I tried using: gulp clean --force but it didn't work. Could someone please clarify what might be causing this issue or what mistake I am making? Your help would be greatly ...

Angular and Spring not cooperating with GET request. What's the issue?

I have been working on integrating a simple GET request to send an Object of type SearchMessage from my Spring Boot server to my Angular client application. After running the server application and verifying that the JSON content is correctly displayed at ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Issues resolving the signature of a parameter in a Typescript decorator within vscode

I encountered an error while attempting to decorate a class in my NestJS service. The Typescript code compiles without any issues, but I am facing this problem only in VSCode. Unable to resolve signature of parameter decorator when called as an expression ...

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

How can I retrieve query parameters passed from an Angular application in PHP?

I'm trying to figure out how to retrieve data from query parameters sent by an Angular application in PHP. Unfortunately, I don't have much experience with PHP. Is there anyone willing to lend a hand? ...

Error in Angular 7: ActivatedRoute paramId returns null value

On page load, I am trying to subscribe to my paramsID, but when I use console.log(), it returns null. I am currently working with Angular 7. Here is my TypeScript code: import { Component, OnInit } from '@angular/core'; import { Activat ...

Troubleshooting connectivity issues between Entities in microORM and Next.js

While trying to run my Next.js application in typescript, I encountered the following error: Error - ReferenceError: Cannot access 'Member' before initialization After consulting the documentation at https://mikro-orm.io/docs/relationships#relat ...