9

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

1
  • Validators.pattern(/^([+]?(([1-9]\d*(\.\d{1,2})?)|0\.(([1-9]\d?)|(\d[1-9]))))$/) try this Commented May 12, 2019 at 9:45

1 Answer 1

27

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]))")
Sign up to request clarification or add additional context in comments.

1 Comment

I had the same issue, i was using a string pattern without double escape the backslashes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.