Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
false

International 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
false

Common 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
false

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.