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

Is it possible to apply CSS to the alert and confirm functions in Angular?

Currently, I am facing an issue with implementing CSS on elements that are nested inside a function. I am unsure of how to access them properly. For example: updateUser() { this.usersService.UpdateUser(this.user.id, this.user) .subscribe(() =& ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

Something went wrong trying to retrieve the compiled source code of https://deno.land/[email protected]/path/mod.ts. It seems the system is unable to locate the specified path. (os error 3)

Upon executing my main.ts script using deno, I encounter the following error message: error: Failed to retrieve compiled source code from https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcccbdbff8f918a86918f"& ...

encountered difficulties while attempting to install npm i due to node-gyp errors

When attempting to run npm i --force, I encounter the following error: pm ERR! code 1 npm ERR! path /Users/moblizeit/GitHub/code-repo/apps/business-card-scanner/admin/businesscardadmin/node_modules/grpc npm ERR! command failed npm ERR! command sh -c -- nod ...

The HTML template remains unchanged unless explicitly triggering detectChanges() with change detection set to onpush

In my Angular component, I am utilizing change detection on push. The component includes an input that gets modified by the component when the route changes. However, I noticed that simply assigning a new reference to the input and making modifications d ...

Generate an event specifically for weekdays using the angular-calendar tool available at https://mattlewis92.github.io/angular-calendar/#/kitchen-sink

I'm currently setting up events for the calendar using . According to the guidelines, events are structured like this : events: CalendarEvent[] = [ { start: subDays(startOfDay(new Date()), 1), end: addDays(new Date(), 1), title ...

React Typescript: The specified argument type cannot be assigned to the parameter type

Creating a Check Box Button React component has resulted in an error related to setRSelected(1) and setRSelected(2)... const [cSelected, setCSelected] = useState([]); const [rSelected, setRSelected] = useState(); const onCheckboxBtnClick = (selected ...

Troubleshooting Angular2: Issues with ngModel functionality within an ngIf directive

Whenever I attempt to reference an NgModel directive using a template reference variable within an *ngIf statement, I encounter a "Cannot read property 'valid' of undefined" error. Consider the following form as an example: <form (ngSubmit)= ...

Understanding Typescript event handling in React

Encountering issues when attempting to build my React/Typescript app using the MouseEvent type in an event handler: private ButtonClickHandler(event: MouseEvent): void { ... } The error message received is as follows: error TS2322: Type '{ onCl ...

Exploring Angular 9: Experimenting with iterating over a collection of objects and performing validations

Forgive me if this is a basic question, but I am new to Angular 9 and json. I am attempting to iterate through a list and only create a table row if the correct ID matches the ID passed from the previous page link. I am struggling to make the if statement ...

What is the best way to set up environments for Google App Engine (GAE

After developing a web app with server and client components, I decided to deploy it to Google Cloud using App Engine. Although the deployment process was successful, the main issue lies in the non-functioning env_variables that are crucial for the applic ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

In TypeScript, leveraging the spread operator to determine the largest value in an array containing nullable numbers

Having an array of nullable numbers presented in the following way: let myArray : Array<number | null> = [1,2,null,4,null,5]; let maximumOfMyArray = Math.max(...myArray); // Type null is not assignable to type number I am content with JavaScript tre ...

Setting a maximum value for an input type date can be achieved by using the attribute max="variable value"

Having trouble setting the current date as the "max" attribute value of an input field, even though I can retrieve the value in the console. Can anyone provide guidance on how to populate the input field with the current date (i.e max="2018-08-21")? var ...

What could be causing the issue of console.log() being called multiple times in Angular when invoking a method through text interpolation?

Utilizing Text interpolation to invoke a method. home.component.html <p>{{myMethod()}}</p> home.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './h ...

The service method call does not occur synchronously

In my OrderServer class, I am utilizing an OrderService to connect to a database and retrieve data every minute. The communication with the web app is handled through SocketIO. Here is a snippet of the code: export class OrderServer { // some required fie ...

When using EmotionJS with TypeScript, the theme type is not properly passed to props when using styled components

CustomEmotions.d.ts import '@emotion/react'; declare module '@emotion/react' { export interface Theme { colors: { primaryColor: string; accentColor: string; }; } } MainApp.tsx import { ...

Utilizing Typescript's baseUrl compiler configuration for node development

Is there a way for node's module loader to support TS's baseUrl compiler option? With the introduction of the baseUrl compiler option in TS 2, project relative require() and import requests are now possible. However, this feature requires that ...

Function 'Once' in Typescript with Generics

Currently, I am utilizing a feature called Once() from FP. In TypeScript, I need to define the types for this function but have been struggling with the implementation. Here's what I have attempted so far: const once = <T, U>(fn: (arg: T) => ...