1

I'd like to check if user input is correct for phone numbers in two formats:

  • 01 1234567 (two numbers, a space, seven numbers)
  • +12 123 123 123 123 (plus sign, two numbers, a space, three numbers, a space, three numbers, a space, three numbers
  • no character at all (no input)

I wrote a regex for this [0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3}|[0-9]{2} [0-9]{7}|. It works when checked with online regex checkers, but it won't work (user can write whatever they want) when used with AngularJS: ng-pattern="[0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3}|[0-9]{2} [0-9]{7}|".

0

1 Answer 1

1

You need to define a regex that will match the whole string that matches your patterns as optional patterns:

ng-pattern="/^(?:\+[0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3}|[0-9]{2} [0-9]{7})?$/"
            ^^                                                           ^^

Or, a bit shorter:

ng-pattern="/^(?:\+[0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/"

If you define the pattern in a JS file as a variable use

var mypattern = /^(?:\+[0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/;

Note that when using regex delimiters the anchors are required for the regex to match entire input.

See the regex demo.

Details

  • ^ - start of string
  • (?: - start of an optional non-capturing group:
    • \+ - a + char
    • [0-9]{2} [0-9]{3} [0-9]{3} [0-9]{3} (equal to [0-9]{2}(?: [0-9]{3}){3}) - 2 digits and then 3 occurrences of a space, 3 digits
  • | - or
    • [0-9]{2} [0-9]{7} - 2 digits, space, 7 digits
  • )? - end of the optional group
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your help! My browser shows the following error SyntaxError: Invalid regular expression: /^(?:+[0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/: Nothing to repeat.
@menteith You did not escape the +. Are you using it inside ng-pattern attribute? If not, use [+].
I my source file (jade) I have ng-pattern="/^(?:[+][0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/" in my output html file I have ng-pattern="/^(?:[+][0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/". There is no error yet user can input anything they want.
@menteith If you define the regex inside a JS file, use var mypattern = /^(?:\+[0-9]{2}(?: [0-9]{3}){3}|[0-9]{2} [0-9]{7})?$/;
@menteith Glad it worked for you. Please also consider upvoting the answer if it turned out helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.