2

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:

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?

1
  • 1
    ^({0,1}...: the {0,1} quantifier repeats nothing. You should read a regex tutorial, in particular about quantifiers and character classes (to avoid useless alternations). Commented Jan 29, 2018 at 4:04

2 Answers 2

2

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}'
)
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Why do I need a custom validator when there is a built-in pattern validator that should do the job?
@Anthony I updated my answer, can you give it a shot and let me know, I'n curious if that would solve the issue.
With the updated answer I get - SyntaxError: 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 at new RegExp (<anonymous>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.