在在线正则表达式测试器中工作时,正则表达式在Angular Validators.pattern()中不起作用 [英] Regex not working in Angular Validators.pattern() while working in online regex testers
问题描述
我已经在Regex101.com上编写并严格测试了一个正则表达式,但是当将其实现到FormControl Validators.pattern方法中时,它将显示出意外的行为.
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.
这是要邮寄包裹的宽度"输入.仅正值,最多2个小数位,最小值(0.01),最大值随后针对API响应进行测试(无关).
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>
以下屏幕截图说明了我在Regex101.com上进行的测试;您可以看到所有应该通过和失败的方案.
The following screenshot illustrates my tests from Regex101.com; you can see all the scenarios that should PASS and FAIL.
但是,正如您在此处看到的那样,任何多位数的值都会使模式失败,这与上面的预期行为相反.
But, as you can see here, any multi-digit value fails the pattern, contrary to the expected behaviour above.
推荐答案
使用以下修复程序:
Validators.pattern(/^\+?(?:[1-9]\d*(?:\.\d{1,2})?|0\.(?:[1-9]\d?|\d[1-9]))$/)
请确保:
- 您将正则表达式定义为 regex文字(不是字符串,
/.../
不应包含任何引号 - 如果您使用字符串模式,请确保先对转义符进行两次转义,然后再也不用在两端使用
^
和$
,因为它们会自动添加.
- 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.
上面的代码等于
Validators.pattern("\\+?(?:[1-9]\\d*(?:\\.\\d{1,2})?|0\\.(?:[1-9]\\d?|\\d[1-9]))")
这篇关于在在线正则表达式测试器中工作时,正则表达式在Angular Validators.pattern()中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!