Angular2/4 Telephone Validation

Viewed 3232

I am trying to implement a form in Angular 2/4. There is a field for Telephone number. I used a regular expression as

pattern="^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$"

in the corresponding input field. It accepts almost all the formats but not the following:

  1. 754-3010 (Local)

  2. (541) 754-3010 (Domestic)

  3. +1-541-754-3010 (international)

More over it should accept +, -, (, and ) characters.

Hope some one can help

1 Answers

You may make a part of the regex optional using an optional non-capturing group.

Use

^\s*(?:\+?\d{1,3})?[- (]*\d{3}(?:[- )]*\d{3})?[- ]*\d{4}(?: *[x/#]\d+)?\s*$
                              ^^^           ^^

See the regex demo

Note that {1} is redundant, you may remove it.

As for the capturing groups, you may keep your original ones if you need them, but if you are just validating, I'd rather remove them.

Details

  • ^ - start of a string
  • \s* - 0+ whitespaces
  • (?:\+?\d{1,3})? - an optional sequence of:
    • \+? - an optional (1 or 0) + symbol
    • \d{1,3} - any 1 to 3 digits
  • [- (]* - a -, space or (
  • \d{3} - any 3 digits
  • (?:[- )]*\d{3})? - an optional sequence of:
    • [- )]* - 0+ -, spaces or )
    • \d{3} - any 3 digits
  • [- ]* - 0+ spaces or -
  • \d{4} - any 4 digits
  • (?: *[x/#]\d+)?
  • \s* - 0+ whitespaces
  • $ - end of string.
Related