JAVASCRIPT
Validate and Format US Phone Numbers with Regex
Learn to validate common 10-digit US phone number formats and extract its components using regular expressions in JavaScript.
function isValidUSPhoneNumber(phoneNumber) {
// Allows formats like (123) 456-7890, 123-456-7890, 123.456.7890, 123 456 7890
const phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
const match = phoneNumber.match(phoneRegex);
if (match) {
// Optional: Reformat to a standard string (e.g., "123-456-7890")
return `${match[1]}-${match[2]}-${match[3]}`;
}
return null; // Or false if just validation is needed
}
// Examples:
// console.log(isValidUSPhoneNumber("(123) 456-7890")); // "123-456-7890"
// console.log(isValidUSPhoneNumber("123-456-7890")); // "123-456-7890"
// console.log(isValidUSPhoneNumber("1234567890")); // "123-456-7890"
// console.log(isValidUSPhoneNumber("invalid-number")); // null
How it works: This JavaScript function uses a regular expression to validate if a given string is a valid 10-digit US phone number, supporting various common separators like parentheses, hyphens, dots, and spaces. If valid, it optionally reformats the number into a standardized "XXX-XXX-XXXX" string using capture groups; otherwise, it returns null.