I've written and rigorously tested a regex on Regex101.com, but when implemented into my FormControl Validators.pattern method, it's displaying unexpected behaviour.

This is for the Width input for a package to be mailed. Only positive values, with a maximum of 2-decimal places, a minimum value being (0.01), and a maximum being tested later against an API response (irrelevant).

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 following screenshot illustrates my tests from Regex101.com; you can see all the scenarios that should PASS and FAIL. Tests from Regex101.com

But, as you can see here, any multi-digit value fails the pattern, contrary to the expected behaviour above.

Production results

2 Answers

4
Wiktor Stribi┼╝ew On Best Solutions

Use the following fix:

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

The regex demo is here.

Make sure:

  • You define the regex as a regex literal (not a string, /.../ should not be wrapped with any quotes
  • If you use a string pattern, make sure you double escape the backslashes and then, you do not need to use ^ and $ at both ends as they will be added automatically.

The code above is equal to

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

You just have to make this change:

<div>
   <input formControlName='maxWidth' type='text' required />

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