Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system.

For instance, the user has already entered these values into the database:

["typescript", "C#", "python"]

If they type one of these existing values exactly into the input field, I want a validation message to appear.

I found a negative look-ahead Regex that somewhat works:

^(?!.*(typescript|C#|python)).*$

However, it will trigger validation error if any of those words appear anywhere in the input string (for example: "pythons" would trigger the error). I only want it to fail if one of those words appears exactly as entered.

UPDATE

I opted for the custom validator solution provided below. The regex approach also worked but validators were deemed more appropriate for this specific issue.

Answer №1

If you are seeking a solution using regex, you can utilize the following regular expression to exclude matches that exactly match any of the following:

typescript
C#
python

To implement the negative look ahead as per your request, it should be typed in this format:

^(?!(?:typescript|C#|python)$).+$

Check out the Regex Demo here

Answer №2

Avoid using regular expressions as they can be excessive, consider utilizing a custom validator instead.

export function usedNames(validNames: string[]): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    if (validNames.includes(control.value)) {
      return null;
    } else {
      return { usedNames: {value: control.value} };
    }
  };
}

Usage (reactive form):

new FormGroup({
  'language': new FormControl(this.hero.name, [
    Validators.required,
    usedNames(['typescript', 'C#', 'python']) // <-- Here's how you pass in the custom validator.
  ]),
  // ... (other inputs)
});

Usage (template form):

@Directive({
  selector: '[appUsedNames]',
  providers: [{provide: NG_VALIDATORS, useExisting: UsedNamesDirective, multi: true}]
})
export class UsedNamesDirective implements Validator {
  @Input('appUsedNames') usedNames: string;

  validate(control: AbstractControl): {[key: string]: any} | null {
    return this.usedNames ? usedNames(this.usedNames)(control) : null;
  }
}

Additionally, consider using a select element instead of an input, or include a list and <datalist> to guide the user on what to type...

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

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...

Generate a series of HTTP requests using an HTTP interceptor

Is it possible to initiate an http request before another ongoing http request finishes (For example, fetching a token/refresh token from the server before the current request completes)? I successfully implemented this functionality using Angular 5' ...

Identify any missing periods and combine the years into a single range

I am working on restructuring year ranges with gaps and consolidating them. For example, converting [{start: 2002, end: 2020}, {start: 2020, end: null}] to {start: 2002, end: null} or [{2002, 2004},{2006, 2008}, {2008, null}] to [{2002-2004}, {2006-null}]. ...

Uploading Images to Imgur with Angular 4

As a newcomer to TypeScript, I am faced with the challenge of uploading an image to the Imgur API using Angular. Currently, my approach involves retrieving the file from a file picker using the following code: let eventObj: MSInputMethodContext = <MSIn ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

Disallow specific sequences of characters

My contact form has been bombarded with spam messages lately. Upon investigation, I have observed a pattern in the content of these messages. The email address field always seems to include the phrase "Staceyrow," while the message field typically contains ...

The use of regular expressions is not equipped to deal with unexpected square brackets

Previously, I received invaluable help from the brilliant minds here which led me to create an exceptional recursive regular expression that enables me to convert custom BBCode-style tags within a block of text. /// <summary> /// A useful class that ...

Google Chrome does not display Set-Cookie header on page loads

Issue Having trouble with the Set-Cookie header not showing up in the response headers when making a request to a Spring Boot server's Post endpoint from an Angular app in Chrome's dev console. Summary of Findings Set-Cookie does appear in res ...

Is it possible to transfer files using web-bluetooth technology?

As I work on developing an embedded system that counts the number of cars, saves their speed and time data in a logs file using rsyslog. Simultaneously, I am creating a web-API (in Typescript/Angular with Electron for Desktop usage and later Web as well) t ...

Tips for deciding on the appropriate CSS for an Angular 6 navbar component

I am currently working on an angular 6 application where users are assigned different roles that require distinct styling. Role 1 uses Stylesheet 1, while Role 2 uses Stylesheet 2. The Navbar component is a crucial part of the overall layout structure of ...

Is it possible to use the provide() method with a string in Angular 2 when writing

I am attempting to utilize a String as a token for providing instead of a class: app.RandomComponent = ng.core .Component({ selector: "randomComponent", template: "Component!", providers: [ ng.core.provide("Stuff", ...

Why is TS1005 triggered for Redux Action Interface with an expectation of '=>'?

I'm finding it difficult to identify what's causing this issue, as shown in the esLint error from Typescript displayed in the screenshot below: https://i.stack.imgur.com/pPZa7.png Below is the complete code, which consists of actions for redux. ...

ESLint version 8.0.0 encountered an error while attempting to fetch the '@typescript-eslint' plugin

Hey there, I'm in need of some assistance. I encountered an error while trying to build a project. Uh-oh! Something didn't go as planned! :( ESLint: 8.0.0 TypeError: Failed to load plugin '@typescript-eslint' specified in ' ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

Combining MSAL ADB2C with Visual Studio 2017 Angular Starter Kit

Currently, I am in the process of integrating Azure B2C into my Angular application. While I have successfully referenced examples from various sources (like VS Code Angular projects) to make MSAL work, I seem to be facing a roadblock when trying to do the ...

Troubleshooting Angular MIME problems with Microsoft Edge

I'm encountering a problem with Angular where after running ng serve and deploying on localhost, the page loads without any issues. However, when I use ng build and deploy remotely, I encounter a MIME error. Failed to load module script: Expected a ...

Intellisense from @reduxjs/toolkit is not showing up in my VS Code editor

My experience with vscode is that intellisense does not recognize @reduxjs/toolkit, even though the code itself is functioning correctly. I have already installed the ES7+ React/Redux/React-Native snippets extension from here. Here are a couple of issues ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

Having trouble invoking the child component when the button is clicked

I am utilizing the ng-sidebar library. My goal is to trigger a child component (sidebar) when a button is clicked, but I am unable to achieve the desired result. For example: Check out this Stackblitz demo Parent TypeScript code: export class AppComponen ...