Is there a more effective way to implement a Custom Validator using .forEach?

I have developed my own validation class as a learning exercise. Do you think this is an effective approach, or do you have suggestions for improvement?

import { AbstractControl } from '@angular/forms';

export class ProjectNameValidator {
   private static blackList = ['Test1'];
    static validateName(control: AbstractControl): {[key: string]: boolean} | null {
       const name: string = control.value;
       let isValid = true;
       ProjectNameValidator.blackList.forEach(forbiddenName => {
           if (forbiddenName === name) {
              isValid = !isValid;
           }
       });
       return isValid ? null : {'Forbidden name': true};
    }
}

Answer №1

To validate the project name, I recommend using the includes method in the following way:

export class ProjectNameValidator {
  private static restrictedNames = ['Blocked', 'Restricted'];
  static validateName(control: AbstractControl): { [key: string]: boolean } | null {
    return ProjectNameValidator.restrictedNames.includes(control.value) ? { 'Invalid name': true } : null;
  }
}

Answer №2

When checking for invalid (forbidden) items in a list, it's important to stop as soon as an invalid item is found. Continuing to check the rest of the list can lead to unintentional permissions being granted if there are an even number of forbidden names.

Instead of looping through the entire list, consider using the indexOf method:

ProjectNameValidator.blackList.indexOf(name) >= 0;

This allows for a quick check to see if the entered value is included in the blackList.

Answer №3

What does my personalized validator look like now?

import { AbstractControl } from '@angular/forms';

export class CustomNameValidator {
   private static restrictedNames = ['Admin', 'Superuser', 'Root'];
    static validateName(control: AbstractControl): {[key: string]: boolean} | null {
       const name: string = control.value;
       const isRestricted =  CustomNameValidator.restrictedNames.includes(name);
       return isRestricted ? {'Invalid Name': true} : null;
    }
}

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

Utilizing Window function for local variable assignment

Currently, I am facing a challenge in my Angular2 service where I am attempting to integrate the LinkedIN javascript SDK provided by script linkedin. The functionality is working as expected for retrieving data from LinkedIN, however, I am encountering an ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

The Same Origin Policy has prevented access to the remote resource located at http://localhost:8082/api/countries due to a Cross-Origin Request Block

Solution The XMLHttpRequest access to 'http://localhost:8082/api/countries' from the origin 'http://localhost:4200' has been blocked by the CORS policy. The response to the preflight request is failing the access control check because t ...

app-root component is not populating properly

As a newcomer to Angular 2, I have embarked on a small project with the following files: app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MaterialModule } fro ...

The connection status of socket.io is always inactive

At this moment, here is what I have. There are three different attempts within the constructor comments. Currently, when the frontend launches, it continuously tries to connect with the backend in socket.io. The backend does receive the connection, but th ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

Guide to setting up a one-to-many self relation entry in Prisma

I am facing a challenge with a simple schema model that includes one-to-many self relations. In this scenario, my goal is to create a parent entity along with its children in a single transaction. How can I accomplish this task effectively? data-model Y{ ...

Having trouble with the ngx-slick-carousel installation

I have been attempting to add the slick-carousel library to my Angular project by following the instructions outlined here: https://www.npmjs.com/package/ngx-slick-carousel. The first two steps, which are: npm install jquery --save npm install slick-caro ...

Clicking on an icon to initiate rotation (Material UI)

Is there a way to toggle the rotation of an icon (IconButton) based on the visibility of a Collapse component? I want it to point down when the Collapse is hidden and up when it's shown. const [expanded, setExpanded] = useState<boolean>(false); ...

Changing application security is threatened by sanitizing base64 images

I'm having some trouble displaying an image that I've converted to base64 encoding. data:image/vnd.microsoft.icon;base64,AAABAAIAICAAA..... No matter what I try, I always end up with the following error: { changingThisBreaksApplicationSecur ...

Combining b2c and b2e integration through Azure Active Directory

Is there an efficient method for combining Azure AD b2c and b2e within an Angular application? Can we provide two separate buttons on the login page and redirect users based on their selection? Alternatively, could social login be utilized, keeping in mi ...

Simultaneously accessing multiple APIs

I am currently facing an issue with calling two API requests sequentially, which is causing unnecessary delays. Can someone please advise me on how to call both APIs simultaneously in order to save time? this.data = await this.processService.workflowAPI1(& ...

Running into issues compiling Ionic 4 with Angular 7 inside a Docker container

Facing Issues Compiling Ionic 4 with Angular 7 in Docker I am trying to compile a project using Ionic 4 and Angular 7 within Docker. Here are the steps I have taken: I manually created an image with Java JDK version 8, following this article How To Ins ...

How can a child component trigger an event in its parent component?

Currently, I have tabs implemented with a form and a button in tab1. In the parent component, there is an event that deactivates the current tab and activates the next one. Can anyone advise on how to call this event from the child component? gotosecond ...

Utilizing indexes to incorporate elements into an object array

I'm currently working on a project using Angular. I have an index coming from the HTML, and here is the code snippet: save(index){ //this method will be called on click of save button } In my component, I have an array structured like this: data = [{ ...

Displaying code within an Angular 2 template

Working on an Angular 2 project and facing a challenge in displaying C# code within the template, which may later be styled with syntax highlighter. The issue arises when attempting to insert the C# code into the Angular 2 template, resulting in template ...

Unable to attach to 'leafletOptions' as it is unrecognized as a property of 'div'

It seems like I keep encountering this problem, which is often resolved by adjusting import statements. Right now, my imports look like this: import { LeafletModule } from 'node_modules/@asymmetrik/ngx-leaflet'; import * as L from 'leaflet& ...

Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I& ...

Running Angular/Rxjs store (ngrx) calls synchronously

After fetching 2 items from my store using ngrx, I need both requests to complete before taking further action. Here's an example of what I'm trying to achieve: const item1$: Observable<Item> = this._store$.select( ItemStoreSelectors.sele ...

various issues with fonts and Uncaught Eval error

I've been encountering multiple font/style errors and an uncaught eval. I have attached a picture for reference. My Angular application is not functioning properly, and I suspect these errors may be the reason. However, I am unsure of their significan ...