JAVASCRIPT
Validate North American Phone Numbers (Flexible Format)
Validate North American phone numbers allowing for various common formats including parentheses, hyphens, spaces, and optional country code with a flexible regex pattern.
const phoneRegex = /^(\+1[\s-]?)?(\(?([0-9]{3})\)?)[\s-]?([0-9]{3})[\s-]?([0-9]{4})$/;
function isValidUSPhone(phoneNumber) {
return phoneRegex.test(phoneNumber);
}
// Examples:
console.log(isValidUSPhone("123-456-7890")); // true
console.log(isValidUSPhone("(123) 456-7890")); // true
console.log(isValidUSPhone("123 456 7890")); // true
console.log(isValidUSPhone("+1 123 456 7890")); // true
console.log(isValidUSPhone("1234567890")); // true
console.log(isValidUSPhone("123-4567")); // false (not enough digits)
console.log(isValidUSPhone("1234567890123")); // false (too many digits)
How it works: This regex pattern validates typical 10-digit North American phone numbers, accommodating common formatting variations. It optionally matches an international country code `+1` with an optional space or hyphen. It then expects three digits, optionally enclosed in parentheses `\(?([0-9]{3})\)?`, followed by optional separators like space or hyphen `[\s-]?`, then another three digits, and finally four digits. The pattern ensures the full string adheres to these structural requirements.