Angular has its own unique way of handling regular expressions through its TypeScript

Considering the creation of an enum to store various regex patterns in my application for enhanced code reuse.

For example:

export enum Regex {
    ONE_PATTERN = /^[example]+$/g,
    ANOTHER_PATTERN = /^[test]{5,7}$/g
}

However:

  1. Encountering the TS90010 error when not using string literals: Type RegExp is not assignable to type Regex.
  2. Unable to use these patterns in a pattern attribute on inputs if using string literals.

For instance:

<input ngModel="..." pattern="{{ANOTHER_PATTERN}}" .../>

Is this approach advisable for storing regex patterns in this manner?

Answer №1

It is not possible to assign a regular expression (`RegExp`) to an enumeration (`enum`), as enumerations can only be either numeric or string-based.

If you want to store the `RegExp`, you have two options:

Option A - Store the `RegExp` as a string in an enumeration

enum RegExpEnum {
    ONE_DANK_REGEX = "^[dank]+$",
    FIVE_OUT_OF_SEVEN = "^[meme]{5,7}$"
}

Option B - Store the `RegExp` in a class/variable

class RegexClass {
    public static readonly ONE_DANK_REGEX = /^[dank]+$/g;
    public static readonly FIVE_OUT_OF_SEVEN = /^[meme]{5,7}$/g;
}

In both cases, you will need to reference the containing enumeration or class in your component by assigning it to a local variable.

@Component({ ... })
public class MyComponent {
    availableRegex = RegExpEnum; // or RegexClass
}

You can then access it in the HTML part of your component.

<input [(ngModel)]="name" [pattern]="availableRegex.ONE_DANK_REGEX"/>

DEMO

Answer №2

Enum can only hold strings and numbers as values.

If you need to store regular expressions, utilize a static class for that purpose.

export class RegularExpression
{
    public static ALPHA_CHARACTERS: RegExp = /([^A-Za-z])+/g;
}

Example of Usage:

'Your_* Name'.replace(RegularExpression.ALPHA_CHARACTERS, '');

Answer №3

It is recommended to follow the option A provided in the accepted response and incorporate it into your code like so:

export enum Patterns {
  ONE_COOL_PATTERN = "^[cool]+$",
  FIVE_TO_TEN_FUN = "^[fun]{5,10}$",
}

public readonly patternOne = new RegExp(Patterns.ONE_COOL_PATTERN, "g");

This approach offers some flexibility when creating the regular expression object.

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

Populate List Items until Maximum Capacity is Reached and Increase the

Is there a way to make a ListItem fill the list vertically while also being able to overflow it if needed? I'm looking for a solution that would allow me to access the height of the empty space in the list, which I believe would be the minHeight. Som ...

Using Typescript to enclose the object and selectively proxying a subset of its methods

When utilizing the Test class within another class named Wrapper, I aim to be able to delegate the methods to the test instance in a universal manner, like so: this.test[method](). In this scenario, my intention is only to delegate the fly, swim, and driv ...

Adding color dynamically to text within ion-card based on a regex pattern

My goal is to enhance the appearance of certain text elements by wrapping them in a span tag whenever a # or a @ symbol is detected, creating the look of usernames and hashtags on Twitter. Below is the code I am currently using: TS FILE: ngOnInit(): void ...

Angular Unit Test with SignalR: An issue occurred during the server negotiation process, resulting in a 'Not Found' error

Currently, I am working on an Angular 9 project with Asp.Net Core that utilizes SignalR. While everything is functioning correctly in the application, I am facing a challenge in performing proper unit testing on the component that integrates the signalr se ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

Troubleshooting Issue with Angular Property Binding for Image Dimensions

Currently, I am exploring property binding in Angular through an example. The idea is to use an image and bind its width, height, and src attributes using property binding. Surprisingly, even though there are no errors and the image renders successfully vi ...

Exploring Angular Ag-Grid: Enhancing Row Expansion with a Simple Click

How can I increase the height of a particular row in Angular Ag Grid when clicked? I've edited the code in Stackbiz. Click here to see the edited data This is an example running from ag grid Tutorial Grid Tutorial Example ...

Can the lib property in tsconfig.json override the target property?

Just starting out with Typescript, I have a query regarding the lib and target properties. Below is my tsconfig.json file: { "compilerOptions": { "target": "es5", "outDir": "./dist", "rootDir": "./src", "noEmitOnError": true, } } //index.ts consol ...

Exploring in Angular 2 by using First Name, Last Name, and Email for queries

Details Currently, I am working on implementing a search functionality using pipes. Users should be able to search by email, first name, or last name. At the moment, it only works for searching by email. I am looking to extend this capability so that user ...

The URL "http://localhost:8100" has been restricted by the CORS policy, as it lacks the necessary 'Access-Control-Allow-Origin' header on the requested resource

`The CORS policy has blocked access to the XMLHttpRequest at 'http://localhost/phpfile/leave-option.php' from the origin 'http://localhost:8100'. This is due to the absence of the 'Access-Control-Allow-Origin' header on the re ...

Exploring Angular 2's ngFor Directive with JSON Data

Recently diving into Angular2, I've been trying to extract data from a JSON file. While I have successfully retrieved the file using a REST client, stored it in a local variable within a component, and accessed certain properties of that variable, I&a ...

Setting default properties for Ionic Components can be achieved by following this guide

Is it possible to set default properties for Ionic components when used with Angular 11? For example, instead of repeating the position for every label, can a meaningful default be enforced for the entire application? <ion-label position="floating ...

Access an external URL by logging in, then return back to the Angular application

I am facing a dilemma with an external URL that I need to access, created by another client. My task is to make a call to this external URL and then return to the home page seamlessly. Here's what I have tried: <button class="altro" titl ...

What is the process for including a version number in npm pack?

I've been working on deploying TeamCity with NPM pack, and I've noticed that it's packaging everything up as filename-0.0.0.tgz. So, I decided to switch to the command line to troubleshoot before running it through TC. When I run npm pack i ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Charging for Firebase together with Server-Side Rendering

Utilizing a simplistic Cloud Function to ascertain whether the incoming request is bot-generated, I then deliver server-rendered content if that criterion is met on an Angular application hosted via Firebase. My understanding leads me to believe that this ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

Uncertain entities in Typescript

I used to use Flow for typing. How can I type an imprecise object? Here's the array I'm working with: const arr = [ {label: 'Set', value: setNumber, id: 'setNumber', set: setSetNumber, type: 'text'}, ...

Customize CSS styles based on Angular material stepper orientation

Is it possible to change the CSS style of an angular material stepper based on its orientation? For instance, can we set a red background when the stepper is displayed vertically and a blue background when horizontal? ...

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...