Angular Reactive Forms模式验证:无效的正则表达式 [英] Angular Reactive Forms pattern validation: Invalid regular expression

查看:47
本文介绍了Angular Reactive Forms模式验证:无效的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AngularJS网站上有一个用于澳大利亚电话号码验证的正则表达式.我已经在反应形式"验证器中设置了确切的模式,如下所示:

I have a regex for Australia phone number validation working in an AngularJS website. I have set the exact pattern in the Reactive Forms validator as follows:

 Validators.pattern(
  '/^({0,1}((0|+61)(2|4|3|7|8))){0,1}( |-){0,1}[0-9]{2}( |-){0,1}[0-9]{2}( |-){0,1}[0-9]{1}( |-){0,1}[0-9]{3}$/'
 )

由于出现以下错误,因此页面无法加载:

The page doesn't load as it gets the following error:

无效的正则表达式:/^/^({0,1}((0 | +61)(2 | 4 | 3 | 7 | 8))){0,1}(|-){0,1} [0-9] {2}(|-){0,1} [0-9] {2}(|-){0,1} [0-9] {1}(|-){0,1} [0-9] {3} $/$/:无需重复

Invalid regular expression: /^/^({0,1}((0|+61)(2|4|3|7|8))){0,1}( |-){0,1}[0-9]{2}( |-){0,1}[0-9]{2}( |-){0,1}[0-9]{1}( |-){0,1}[0-9]{3}$/$/: Nothing to repeat

使用反应式表单时指定此模式的正确方法是什么?

What is the correct way to specify this pattern when using Reactive Forms?

推荐答案

存在多个问题:

  • 不应在引号内使用正则表达式文字(或使用带有双转义特殊字符的字符串模式)
  • 必须转义特殊字符,例如() + -无可重复是由((捕获组的开始)是用 {0,1} 进行量化的事实,这是一个错误
  • {0,1} 等于?(|-)可以写为 [-] (2 | 4 | 3 | 7 | 8)可以写为 [23478] .
  • The regex literal should not be used inside quotes (or use a string pattern with double escaped special chars)
  • Special chars like (, ) and + must be escaped - nothing to repeat is caused by the fact that ( (start of a capturing group) is quantified with {0,1} and that is an error
  • {0,1} is equal to ?, ( |-) can be written as [ -], (2|4|3|7|8) canbe written shorter as [23478].

因此,您可以使用

Validators.pattern(
  '^\\(?(0|\\+61)[24378]\\)?[ -]?[0-9]{2}[ -]?[0-9]{2}[ -]?[0-9][ -]?[0-9]{3}$'
)

请注意,您甚至可以在此处省略 ^ $ ,因为锚点将由Angular自动添加到字符串模式中.

Note that you may even omit ^ and $ here since the anchors will be added by Angular automatically to the string pattern.

注意:如果分隔符应该一致,请捕获第一个分隔符,然后对组值使用反向引用:

NOTE: if the separators should be consistent, capture the first one and then use backreferences to the group value:

Validators.pattern(
  '\\(?(?:0|\\+61)[24378]\\)?([ -]?)[0-9]{2}\\1[0-9]{2}\\1[0-9]\\1[0-9]{3}'
)

这篇关于Angular Reactive Forms模式验证:无效的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆