[英]Pattern validator is invalid for IP address regex
I'm using the following regex to validate IP address pattern : 我正在使用以下正则表达式来验证IP地址模式 :
/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/
I also checked it in a regex tester and it works fine. 我也在正则表达式测试器中对其进行了检查,并且工作正常。
However, when I use it in the pattern validator, valid ip addresses (eg: 128.129.80.66) aren't recognized as valid. 但是,当我在模式验证器中使用它时,有效的IP地址(例如:128.129.80.66)不会被识别为有效。
app.component.ts : app.component.ts:
export class AppComponent implements OnInit {
testForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
const ipPattern =
'/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/';
this.testForm = this.fb.group({
inp: ['128.129.80.66', Validators.pattern(ipPattern)]
});
}
}
app.component.html app.component.html
<form novalidate [formGroup]="testForm">
<input formControlName="inp"/>
{{testForm.status}}
</form>
The result: 结果:
What is wrong with this code? 此代码有什么问题?
Since you are using Validators.pattern
, you do not need to anchor the pattern manually (no need for word boundaries, angular will enclose the whole pattern with ^
and $
automatically) and you need to define it properly with a string literal doubling the escaping backslashes, else they will be removed by JS. 由于您使用的是
Validators.pattern
,因此无需手动锚定模式(不需要单词边界,angular会自动将整个模式用^
和$
括起来),并且您需要使用字符串常量将其正确地加倍以正确定义它反斜杠,否则它们将被JS删除。
Use 采用
const ipPattern =
"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
You may add ^
at the start and $
at the end just in case you want to keep the pattern explicit (it does not do any harm to have two ^
at the pattern start and $$
at the end, just the engine will check the start/end of the string positions twice). 您可以在开头添加
^
,在末尾添加$
,以防万一您想使模式保持明确(如果在模式开头有两个^
,在结尾有$$
,则不会有任何危害,只是引擎会检查字符串位置的开始/结束两次)。
NOTE : if you have more complex patterns with alternations, it is a good idea to use ^
and $
explicitly in those patterns since angular automatic anchoring does not enclose the whole pattern with an optional non-capturing group, it just appends ^
and $
to the provided pattern. 注意 :如果您具有更复杂的交替模式,则在这些模式中显式使用
^
和$
是个好主意,因为角度自动锚定不会将整个模式与可选的非捕获组一起包围,而是将^
和$
附加到提供的模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.