JAVASCRIPT

Validate Flexible International Phone Numbers

Validate various international phone number formats including optional country codes, spaces, and dashes using a robust JavaScript regex pattern.

function isValidPhoneNumber(phoneNumber) {
  // Matches: optional leading '+', optional country code (1-3 digits),
  // then various groups of 2-9 digits separated by spaces, hyphens, or parentheses.
  // This pattern is quite flexible and covers many common international formats.
  const phoneRegex = /^\+?(\d{1,3}[-.\s]?)?(\(\d{2,4}\)|\d{2,4})[-.\s]?\d{2,4}[-.\s]?\d{2,9}$/;
  return phoneRegex.test(phoneNumber);
}

// Examples:
// console.log(isValidPhoneNumber('+1 (555) 123-4567')); // true
// console.log(isValidPhoneNumber('555-123-4567'));       // true
// console.log(isValidPhoneNumber('001 555 123 4567'));  // true
// console.log(isValidPhoneNumber('+44 20 7123 4567')); // true
// console.log(isValidPhoneNumber('123'));             // false (too short)
How it works: This JavaScript function `isValidPhoneNumber` uses a regular expression to validate a string against common international phone number formats. The regex allows for an an optional leading plus sign (`\+?`), an optional country code (`\d{1,3}`), and various combinations of digits, spaces, hyphens, and parentheses for the local number part. It's designed to be flexible, accommodating different regional conventions while ensuring a reasonable structure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs