JAVASCRIPT

Validate International Phone Numbers

Implement a flexible JavaScript regex to validate international phone numbers, supporting various formats including optional country codes, spaces, and hyphens.

function validateInternationalPhoneNumber(number) {
  // Regex allows: optional + prefix, optional country code (1-3 digits),
  // then 7-15 digits, possibly with spaces, hyphens, or parentheses
  const phoneRegex = /^\+?(\d{1,3})?[-.\s]?\(?\d{2,4}\)?[-.\s]?\d{3,4}[-.\s]?\d{3,4}$/;
  return phoneRegex.test(number);
}

// Example usage:
console.log(validateInternationalPhoneNumber("+1 (555) 123-4567")); // true
console.log(validateInternationalPhoneNumber("07911 123456")); // true
console.log(validateInternationalPhoneNumber("555-123-4567")); // true
console.log(validateInternationalPhoneNumber("123")); // false
How it works: This JavaScript function `validateInternationalPhoneNumber` employs a regular expression to validate various formats of phone numbers, crucial for global user input. The pattern is designed to be flexible, accommodating optional international dialing codes, common separators like spaces, hyphens, and parentheses, and ensuring a reasonable total length for the numeric digits to match common global communication standards.

Need help integrating this into your project?

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

Hire DigitalCodeLabs