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
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}$/')
There are multiple issues:
(
, )
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}'
)