How to validate a phone number
Short answer
People write phones with spaces, brackets and hyphens. Remove everything except digits and a leading plus, then check the length:
const normalizePhone = (value) => value.trim().replace(/(?!^\+)[^\d]/g, '');
const isPhone = (value) => /^\+?\d{7,15}$/.test(normalizePhone(value));
console.log(normalizePhone('+1 (555) 123-45-67'));
console.log(isPhone('+1 (555) 123-45-67'));
console.log(isPhone('12-34'));Output:
+15551234567
true
falseInternational format
The international E.164 format is a plus and up to 15 digits, without a leading zero:
const isE164 = (value) => /^\+[1-9]\d{6,14}$/.test(value);
console.log(isE164('+15551234567'));
console.log(isE164('5551234567'));Output:
true
falseCommon mistake
A strict pattern for one country rejects phones from other countries and ordinary ways of writing them. Store the normalized number and check only the basics.
const tooStrict = /^\(\d{3}\) \d{3}-\d{4}$/;
console.log(tooStrict.test('(555) 123-4567'));
console.log(tooStrict.test('555 123 4567'));Output:
true
falseFunctions used in this recipe
- String.prototype.replace — Replaces the first match (or all of them with a regex g flag).
- RegExp.prototype.test — Checks whether a string matches a pattern.