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

retrieve the initial subarray from the array using rxjs

Looking to extract the first array from a subarray, my current setup is as follows: Map: map; Map() { Service }); } This is the interface structure: export interface map { } Encountering an error message: ERROR TypeError: ...

Void represents the equivalence of a textual representation

Currently, I am working with Angular and TypeScript. Here is an example of my request: getOrders(this.value.id, null, null).subscribe((response) => { this.ordersArray = response }) I am facing an issue where the value null is being converted to "nul ...

"Exploring the methods to retrieve Firebase authentication error details and outputting the console log message along with

When I encounter an error in Firebase authentication, I want to display it in the console log. However, nothing is being logged and the catch block is not even getting executed. I am unsure about why this is happening and how to retrieve the error code and ...

Optimizing Node.js and Express routes by separating them into individual files: a

When using Express in a Node project along with Typescript, what are the best practices for express.Router? For instance, it is recommended to follow a directory structure like this: |directory_name ---server.js |--node_modules |--routes ---in ...

Collaborate on code for a cross-platform mobile application and a traditional desktop web application

I have a vision to create a cutting-edge app that can be utilized as both a hybrid mobile application and a desktop web application. For the most part, the logic and user interface will remain consistent across both versions. However, there are a few key ...

The AngularJS Service fails to properly convert incoming Json Responses into Model objects during piping

I have been studying AngularJS 17 and recently developed a login application. However, I am facing an issue where the server response is not being properly mapped to the object in the Model Class. Response: { "id": 1, "userName& ...

Pixijs is unable to load spritesheets correctly

I am currently facing an issue while trying to load a spritesheet in PixiJS following the instructions provided on Below is the code snippet I am using: PIXI.Loader.shared.add('sheet', require('../assets/spritesheet.json')).load(sprite ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

How do I implement branch code using TypeScript types in Svelte?

Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors. I am dealing with an array called collectabl ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Display the initial user setup component exclusively during the first login

Within my app.component.html, I have two components named intial-settings and app-navbar: <initial-settings *ngIf="!userFloor"></initial-settings> <app-navbar *ngIf="userFloor"></app-navbar> In my app.component ...

Detecting changes in Angular2 through a commonly shared service

I have a parent function called ngOnInit() that retrieves value from Google Maps as shown below: instance.input = document.getElementById('google_places_ac'); autocomplete = new google.maps.places.Autocomplete(instance.input, { types: [& ...

What is the best way to transform a string array into a number array?

I'm attempting to convert a string array into a number array and after conducting some research online, I came across this solution: let numbersAsStringArray = originalQueryParams[property] ?? [] let numbers = numbersAsStringArray.map((i) => ...

iMask Angular plugin: the unmask feature prohibits typing

I've integrated the iMask plugin with Angular and encountered an issue when setting the value of the unmask attribute to 'typed'. This error only occurs with 'typed' as the value, not 'true' or 'false'. Here&ap ...

Angular Universal (SSR) 'Selectors were not applied as rules were not followed'

Steps to Reproduce: ng new testproject --style scss cd testproject ng add @ng-bootstrap/ng-bootstrap npm run build This issue is not limited to ng-bootstrap, it can occur with other frameworks like bootstrap or tailwind that use SCSS. Error Description: ...

Encountering Issue: NG0303 - Unable to associate 'ng-If' as it is not recognized as a valid attribute of 'app-grocery'

NG0303: Encountering an issue with binding to 'ng-If' as it is not recognized as a valid property of 'app-grocery'. A similar problem was found here but did not provide a solution Despite importing CommonModule in app.modules.ts, I am ...

Can you use `keyof` to create a template literal type?

Defined a form schema type example: type FormSchema = { username: string; settings: { theme: string; language: string } } Now, trying to define the Form Input type like this: type FormInput = { id: keyof FormSchema | `${keyof FormSchema}.${string}` } Enc ...

The hierarchy of precedence when using the TypeScript Type Assertion operator

Is it necessary to wrap the js-ternary operator with 'as' Type Assertion? ios ? TouchableOpacity : View as React.ElementType Will it automatically use the result of '?:' since it comes first? Or would a better implementation be: (ios ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

The NextJS API route functions flawlessly when tested locally, generating over 200 records. However, upon deployment to Vercel, the functionality seems to

Here is the API route that I am using: https://i.stack.imgur.com/OXaEx.png Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import axios from "axios"; import prisma from "../../../lib/prisma ...