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}|".

menteith
  • 596
  • 14
  • 51

1 Answers1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 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 Dec 21 '18 at 12:10
  • @menteith You did not escape the `+`. Are you using it inside `ng-pattern` attribute? If not, use `[+]`. – Wiktor Stribiżew Dec 21 '18 at 12:11
  • 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 Dec 21 '18 at 12:17
  • @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})?$/;` – Wiktor Stribiżew Dec 21 '18 at 12:19
  • @menteith Glad it worked for you. Please also consider upvoting the answer if it turned out helpful. – Wiktor Stribiżew Dec 25 '18 at 09:44