In depth
Four checks on the same six inputs
This table is the honest answer to "should I use a regex?". It ran four checks on six real inputs: the common ten-digit regex, the generic E.164 regex, the US-specific pattern from libphonenumber's data, and the library itself with the US as default country.
| Input | ^\d{10}$ | E.164 regex | US pattern + code | Library isValid() |
|---|---|---|---|---|
| 4155552671 | true | false | false | true |
| +14155552671 | false | true | true | true |
| (415) 555-2671 | false | false | false | true |
| +44 20 7946 0958 | false | false | false | true |
| 0000000000 | true | false | false | false |
| +1 415 555 267 | false | false | false | false |
How to read the table
- The ten-digit regex accepts 0000000000, which is not a real number, and rejects every number with a plus sign or brackets.
- The generic E.164 regex only checks the shape, so it accepts any country and any digits as long as the plus sign and length are right.
- The country pattern checks the digits for one country, but it cannot clean up input like (415) 555-2671 first.
- The library cleans the input, finds the country and validates, which is why it is the only column that handles all six.
Where the country patterns come from
The patterns on this page are read straight from libphonenumber-js's own metadata, which is derived from Google's numbering plan data, not written by hand. They match the national number only, so the international pattern adds the plus sign and the country code in front. Numbering plans change, so regenerate the pattern when you update the library.
When a regex is the right tool
Use a regex when you need an instant shape check in a form field, or when you cannot add a dependency. For anything that sends a message, saves a record or costs money, use the library.