JAVASCRIPT

Validating North American Phone Numbers (NPA-NXX-XXXX)

Validate common North American phone number formats (e.g., (123) 456-7890, 123-456-7890) using a flexible regex in JavaScript.

function isValidPhoneNumber(phoneNumber) {
  // Matches formats like (123) 456-7890, 123-456-7890, 123.456.7890, 123 456 7890
  const phoneRegex = /^(\([0-9]{3}\)|[0-9]{3})[- .]?([0-9]{3})[- .]?([0-9]{4})$/;
  return phoneRegex.test(phoneNumber);
}

// Examples:
// console.log(isValidPhoneNumber('(123) 456-7890')); // true
// console.log(isValidPhoneNumber('123-456-7890')); // true
// console.log(isValidPhoneNumber('123.456.7890')); // true
// console.log(isValidPhoneNumber('123 456 7890')); // true
// console.log(isValidPhoneNumber('1234567890')); // false (no separators)
// console.log(isValidPhoneNumber('123-456-789')); // false (too short)
How it works: This JavaScript function validates strings against common North American phone number formats. The regular expression allows for optional parentheses around the area code, and optional separators (hyphen, space, or dot) between the number groups, ensuring a standard 10-digit number structure (NPA-NXX-XXXX).

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs