Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

Regex not working in Angular Validators.pattern() while working in online regex testers

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]))")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...