Angular Validators.pattern() does not seem to function properly, despite yielding successful results in online regex testers

I have developed a regex pattern on Regex101.com and thoroughly tested it. However, when I applied it to my FormControl Validators.pattern method, it is exhibiting unexpected behavior.

This regex pattern is meant for validating the Width input of a package that will be sent through mail. It should only accept positive values with up to 2 decimal places, a minimum value of 0.01, and the maximum value will be validated later against an API response (not relevant at the moment).

package_validation_messages = {
   'maxWidth': [
      {type: 'required', message: 'Width is required.'},
      {type: 'pattern', message: 'Invalid Width.'}
   ]
};
this.packageSizeForm = this.formBuilder.group({
   maxWidth: new FormControl('', Validators.compose([
      Validators.pattern('^([+]?(([1-9]\d*(\.\d{1,2})?)|0\.(([1-9]\d?)|(\d[1-9]))))$'),
      Validators.required
   ]))
});
<div>
   <input formControlName='maxWidth' type='text' required />

   <span *ngFor="let validation of package_validation_messages.maxWidth">
      <span *ngIf="packageSizeForm.get('maxWidth').hasError(validation.type) && (packageSizeForm.get('maxWidth').dirty || packageSizeForm.get('maxWidth').touched)">{{validation.message}}</span>
   </span>
</div>

The screenshot below showcases the results of my tests conducted on Regex101.com, demonstrating both passing and failing scenarios according to expectations.

However, upon implementation, it appears that the pattern fails to validate multi-digit values, which is contrary to the expected outcome described earlier.

Answer №1

Here is a suggested solution:

Validators.pattern(/^\+?(?:[1-9]\d*(?:\.\d{1,2})?|0\.(?:[1-9]\d?|\d[1-9]))$/)

To see the demonstration of this regex pattern, click here.

Key points to note:

  • Define the regex as a regex literal (do not wrap with quotes like /.../)
  • If using a string pattern, ensure you double escape the backslashes and avoid adding ^ and $ at both ends manually.

The code snippet provided can also be written as follows:

Validators.pattern("\\+?(?:[1-9]\\d*(?:\\.\\d{1,2})?|0\\.(?:[1-9]\\d?|\\d[1-9]))")

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

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

experimenting with a component function triggering the execution of a separate method

Consider the following basic component : import { Component} from '@angular/core'; @Component({ selector: 'app-component' }) export class AppComponent { foo() { this.bar(); } bar() { console.log('hello'); ...

Using Dropbox for seamless navigation

My navigation using Dropbox is not redirecting to the selected page as expected. Below, I have provided code and a demo for your reference. App Routing Module import { NgModule } from '@angular/core'; import { CommonModule } from '@angular ...

Break down a data structure into a type that includes multiple options

Is it possible for Typescript to support type or interface "destructuring" (if that's the right term)? I am attempting to achieve something similar to the code snippet below: type SomeRandomType = { propertyOne: string; propertyTwo: number; ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Why is it that when I try to create a table using the "Create Table" statement, I keep getting an error saying "Near '(': syntax error"?

Error : There seems to be a syntax error near "(". Here is the SQL statement causing the issue: CREATE TABLE IF NOT EXISTS tickets ( numero INTEGER PRIMARY KEY AUTOINCREMENT, identifier VARCHAR(4) NOT NULL, subject VARCHAR(150) NOT NULL, ...

Incorporating a Symbol into a Function

Reviewing the following code snippet: namespace Add { type AddType = { (x: number, y: number): number; }; const add: AddType = (x: number, y: number) => { return x + y; }; } Can a 'unique symbol' be added to the AddType lik ...

Tips for dynamically injecting HTML content in an Angular web application

I'm currently working on an angular website dedicated to a specific book. One of the features I want to include is the ability for users to select a chapter and view an excerpt from that chapter in HTML format. However, I'm facing a challenge wh ...

Combine arrays of objects by comparing two attributes in Typescript

Suppose I have an array in TypeScript that looks like this: const array = [ { id_m: "123", period: "Q1/22", amount: 1000 }, { id_m: "123", period: "Q1/22", amount: 500 }, { id_m: "123&q ...

Unable to reach the exposed port of the container

I am having difficulty accessing an Angular application that I have deployed within a container. Despite exposing the port in my Dockerfile and mapping the port in the docker-compose file, I still cannot access it from my web browser (Mozilla). There are ...

What impact do passing children have on the occurrence of Typescript errors?

Recently, I came across a peculiar situation where the Typescript compiler appeared to be confused by passing the children prop to a component, leading to unsafe behavior. I am looking to create a component that can only accept the subtitle (text) and sub ...

Sharing Photos Through Social Media Platforms with Ionic Plugin

When generating a QR code, I would like to share it via a Social Sharing Plugin. Below is the code snippet I am using to achieve this: share() { let currentImage= "data:image/jpeg;base64,"+ this.createdCode; this.socialSharing.share("QR Image to share", ...

Using a function from one class within another class by passing it as a prop

Below are the methods found in my Search.tsx class. renderSuggestion(suggestion) { <div className="buttons"> <button className="button">View Location</button> <button className="button whitebutton" onClick={this.h ...

Initiate a function once the innerHTML content in Angular has been completely loaded

I'm curious to know if it's possible in Angular to receive a notification when the Inner HTML has finished loading. I have a web application that retrieves an SVG image from a server and I need to display it as innerHTML in order to interact with ...

Issue with validating the date picker when updating user information

Trying to manage user accounts through a dialog form for adding and updating operations, where the type of operation is determined by a variable injected from the main component. Encountered an issue while launching the update process - the date picker tri ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

What is the way to retrieve an array property in a typescript interface?

Imagine a scenario with three interfaces structured as follows: registration-pivot.ts export interface RegistrationPivot { THead: RegistrationPivotRow; TBody: RegistrationPivotRow[]; } registration-pivot-row.ts export interface RegistrationPivotR ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

Issue with onDblClick event in Angular5 and PrimeNG's p-listbox

I encountered an issue while using p-listbox's onDblClick event as it does not return the selected list element. Instead, the event object only contains the value of 'this'. {"originalEvent":{"isTrusted":true}} HTML Blockquote <!-- S ...

How can one retrieve the selected value from a dropdown menu in Angular?

Objective: My goal is to create a dropdown menu where users can select a value, which will then dynamically change the address of the website based on their selection. Issue: Although I managed to make the address change upon selection, it did so for ever ...