模式验证器对于IP地址正则表达式无效 [英] Pattern validator is invalid for IP address regex
问题描述
我正在使用以下正则表达式来验证 IP地址格式:
I'm using the following regex to validate IP address pattern:
/\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/
我还在 regex测试器中进行了检查,它工作正常.
但是,当我在模式验证器中使用它时,有效的IP地址(例如:128.129.80.66)不会被识别为有效.
However, when I use it in the pattern validator, valid ip addresses (e.g: 128.129.80.66) aren't recognized as valid.
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
<form novalidate [formGroup]="testForm">
<input formControlName="inp"/>
{{testForm.status}}
</form>
结果:
此代码有什么问题?
推荐答案
由于使用的是Validators.pattern
,因此无需手动锚定模式(不需要词边界,角度会将整个模式用$
自动),则需要使用字符串文字加倍转义的反斜杠来正确定义它,否则它们将被JS删除.
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.
使用
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.
这篇关于模式验证器对于IP地址正则表达式无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!