menteith
menteith

Reputation: 678

Valid regex expressions won't work with AngularJS

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

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

Upvotes: 1

Views: 175

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

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.

Upvotes: 1

Related Questions