Angular Reactive Forms pattern validation: Invalid regular expression

前端 未结 2 1000
隐瞒了意图╮
隐瞒了意图╮ 2021-01-27 02:53

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:

 V         


        
相关标签:
2条回答
  • 2021-01-27 03:27

    Pass pattern as string, without / which are the delimiters for regex

    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}$/')

    0 讨论(0)
  • 2021-01-27 03:28

    There are multiple issues:

    • 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].

    So, you may use

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

    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}'
    )
    
    0 讨论(0)
提交回复
热议问题