Search code examples
javascriptjqueryregexpreg-match

how to validate specific phone number using javascript


I have a specific format of phone number such as

USA (+1) 000-000-0000

And I want to write a regex for this one. country code can be change but rest of the format should be same all the time. please help.


Solution

  • You can use REGEX in order to define a pattern, /^\w+ \(\+\d+\) \d{3}\-\d{3}\-\d{4}$/ will do the trick.

    const pones = [
      'USA (+1) 000-000-0000',
      'USA (+12) 123-123-5656',
      'OTHERCOUNTRY (+1) 000-000-0000',
      'USA (+1) 1000-000-0000',
      'USA (+1) 000-1000-0000',
      'USA (+1) 000-000-10000',
    ];
    const phoneRegex = /^\w+ \(\+\d+\) \d{3}\-\d{3}\-\d{4}$/
    
    console.log(pones.map(phone => phoneRegex.test(phone)))