A regex will not validate phone numbers correctly. I promise. Numbering plans vary by country, mobile vs landline prefixes differ, and some countries have variable-length numbers. Google's libphonenumber (the library that powers Android's dialer) is the only sane way to do this client- or server-side.
import parsePhoneNumberFromString from "libphonenumber-js";
const parsed = parsePhoneNumberFromString("+49 170 1234567");
console.log(parsed.isValid()); // true
console.log(parsed.country); // "DE"
console.log(parsed.formatInternational()); // "+49 170 1234567"
Two gotchas that catch people out: numbers without a country code need a defaultCountry hint or parsing will silently fail, and "valid" only means "matches the numbering plan" — it says nothing about whether the number is currently assigned to someone.
For a stateless HTTP version of this (useful if your stack isn't JS, or you don't want the dependency), I built it as one of the endpoints on Validate — same libphonenumber-js under the hood, just over JSON. Same account also covers QR API and Currency API.
Top comments (0)