【问题标题】:Pattern validator is invalid for IP address regex模式验证器对 IP 地址正则表达式无效
【发布时间】:2019-01-21 23:17:52
【问题描述】:

我正在使用以下正则表达式来验证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 tester 中检查了它,它工作正常。

但是,当我在模式验证器中使用它时,有效的 IP 地址(例如:128.129.80.66)不会被识别为有效。

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>

结果:

这段代码有什么问题?

【问题讨论】:

    标签: regex angular typescript


    【解决方案1】:

    由于您使用的是Validators.pattern,因此您不需要手动锚定模式(不需要单词边界,角度会自动用^$包围整个模式)并且您需要正确定义它使用字符串文字将转义的反斜杠加倍,否则它们将被 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]?)";
    

    您可以在开头添加 ^ 并在末尾添加 $ 以防万一您想保持模式明确(在模式开头有两个 ^$$ 没有任何害处最后,只有引擎会检查字符串位置的开始/结束两次)。

    注意:如果您有更复杂的交替模式,最好在这些模式中明确使用^$,因为角度自动锚定不会用一个可选的非捕获组,它只是将^$ 附加到提供的模式。

    【讨论】:

      猜你喜欢
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2011-06-20
      • 2017-03-15
      相关资源
      最近更新 更多