The logic behind regular expressions

Currently working on building a web application with Angular 6 and I have a query: I'm in the process of developing a custom input component (specifically for text inputs) like so:

@Component({
  selector: 'input-text',
  templateUrl: './input-text.component.html'
  ]
})
export class InputTextComponent {

  @Input() pattern?: string;

}

I want to enable users to insert a regular expression for validating the input field, like this:

<input-text pattern="^[a-z0-9_-]{8,15}$"></input-text>

The template of my component is structured as follows:

<input type="text" [attr.pattern]="pattern"/>

Regrettably, I lack any knowledge pertaining to regular expressions. There are two things I aim to accomplish:

1 - Develop a method that verifies the validity of the regular expression and alters the visual style accordingly.

2 - Ensure that when the input (with a pattern attribute) is included in a form, the form.valid attribute remains false until the expression is valid. Appreciate your assistance!

Answer №1

  1. Verify the correctness of regex

To ensure the validity of your regular expression, you can handle exceptions thrown by the RegExp constructor during instantiation.

try {
  const regex = new RegExp(pattern);
} catch (error) {
  // If an error occurs, it indicates that the regex pattern is incorrect
  console.error(error.message)
}
  1. Modify the appearance

To change the visual style of your input, you can use the ngClass attribute. If you encounter an error within the catch statement, set a boolean variable to indicate a styling change like this:

private hasBadInput: boolean;
// [...]
catch (error) {
  hasBadInput = true;
}

Then apply the specific class in such cases:

<input-text [ngClass]="{'yourErrorClass': hasBadInput}"><input-text>
  1. Ensuring form correctness

Using [attr.pattern] was a good approach, and the form should automatically adhere to the specified pattern. It's recommended to test your form with a predefined regex before using the dynamic one.
Refer to the official Angular 2+ forms guide for detailed instructions on creating forms.

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

Tips for obtaining a reference to the ngfor-list with a pipe implemented on it

When applying a filter to a list within an ngFor directive, such as *ngFor="data | pipe", it can be challenging to access the filtered data in the component class. One attempted solution is using *ngFor="data | pipe as filtereddata", but this approach seem ...

How to use grepl to identify the first character in a string

Forgive me if this question has already been asked, but after spending the last couple of hours on stackoverflow, I still haven't found a solution. I attempted to use grepl to identify rows that start with a digit. Here's what I tried, but it di ...

The entity is not validated by class-validator

Is it possible to utilize class-validator for validating columns in an Entity? The validation does not seem to work for columns: import { IsEmail } from 'class-validator'; @Entity() export class Admin extends BaseEntity { @Column({ unique: t ...

Creating object types in typescript from object keys: a step-by-step guide

In my JavaScript object, I have two keys named foo and bar. const x = { foo: '', bar: '' } I also have a function called abc that takes a value (which can only be either foo or bar). function abc(value: string) { const selected = x[v ...

Creating adaptable Object Properties using Zod

Just dipping my toes into Typescript, Zod, and Trpc. Let's say I have a schema for animals and plants. I want to keep all their shared properties in the main part of the schema, while putting more specific details into a sub-object named custom. (jus ...

Exploring nested JSON objects within an array using ngFor directive

My application uses Angular 6 and Firebase. I am trying to showcase a list of all appointments. Below is my approach: service.ts getRDV() { this.rdvList = this.firebase.list('/rdv'); return this.rdvList; } Model: export class RDV { key: ...

Using SignalR to implement CRUD operations within a Hub or Controller

I have been working on an Angular app that is built on top of an ASP.NET MVC application. In this project, I have a Dashboard where I showcase Average and Total numbers that are altered during Create / Update / Delete events. Usually, these events are hand ...

Exploring Angular Testing: Unraveling Chained HTTP Requests with the Power of rxjs

I've been attempting to write unit tests for a function in my service that carries out a POST request followed by a GET request. I'm using switchMap to handle this, but running into an issue where the HttpTestingController match function isn&apos ...

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 ...

Why is my Angular promise unexpectedly landing in the error callback?

I am facing an issue with my Angular + Typescript client. I have developed a PHP API and need to send a post request to it. Upon receiving the request, the server fills the response body with the correct data (verified through server debugging). However, w ...

The issue of sending a POST request with form-data body parameters is not functioning as expected in Angular 2

I have successfully sent a file and other parameters in the body with type 'form-data' using Postman. Now, I am trying to achieve the same functionality in Angular 2. Please refer to the screenshot of the request made in Postman: https://i.stack. ...

Instantiate a fresh object with its own set of functions

I've been struggling with implementing the OnPush change detection strategy. Here is an example of a class I have: class Item { private name; private _valid; public set valid(valid) { this._valid = valid; } constructor(name) { th ...

Angular 11 Working with template-driven model within a directive

My currency directive in Angular 8.2 formats currency fields for users by using the following code: <input [(ngModel)]="currentEmployment.monthlyIncome" currency> @Directive({ selector: '[ngModel][currency]', providers: [Curr ...

How to make an optional prop with a default value non-nullable in a ts+react component?

Is there a way to modify a React component to accept an optional prop and then treat it as non-null within the component itself? For example, consider the following basic component: import React from 'react'; type props = { x?: number; }; c ...

Annoying glitch when using http get in Ionic (version 3.19.0)

Issue: Having trouble with Ionic's http get function, as I keep running into this error message: Typescript Error Expected 1-2 arguments, but got 3. The line causing the problem seems to be similar to this: this.http.get('http://127.0.0.1 ...

Unable to resolve the Typescript module within a different file

I am in the process of transitioning my React app to TypeScript. Currently, everything is working fine. However, I encountered an issue after adding the TypeScript compiler and renaming files to .ts and .tsx extensions - it is now throwing a "module not fo ...

Converting a TypeScript class to a plain JavaScript object using class-transformer

I have a few instances of TypeScript classes in my Angular app that I need to save to Firebase. However, Firebase does not support custom classes, so I stumbled upon this library: https://github.com/typestack/class-transformer which seems to be a good fit ...

Error message: The function _this.$(...).modal is not defined for the OpaqueToken jQuery in Angular-cli

I'm facing an issue with using jQuery in Angular2. I can't seem to get my modal to pop out. Error message: I used Angular-cli npm install and then yarn to install bootstrap + In my .angular-cli.json file, I have the following scripts: "script ...

What is the syntax for implementing this function in TypeScript?

When developing applications in react and typescript, I find myself frequently creating helper functions. However, there are two key points that always give me pause. One of my functions is provided below, showcasing the common dilemmas I face. What shoul ...

Unable to convert JSON data for integration with rxjs

I am currently using a webSocket to receive data from my server. I have created an rx Subject called MessageEvent that allows me to retrieve the data. However, although I can successfully log the JSON data in my observable, I am unable to access any prope ...