PYTHON

Validate US/International Phone Numbers

Use a Python regular expression to validate various formats of US and basic international phone numbers, supporting optional country codes and common separators.

import re

# This regex supports formats like:
# +1 (555) 123-4567
# 555-123-4567
# (555) 123-4567
# 5551234567
# +44 20 7123 4567 (basic international)
phone_regex = re.compile(r"^(?:\\+\\d{1,3}[-.\\s]?)?\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}$")

def is_valid_phone_number(phone_number):
    return bool(phone_regex.fullmatch(phone_number))

# Examples
print(is_valid_phone_number("+1 (555) 123-4567")) # True
print(is_valid_phone_number("555-123-4567")) # True
print(is_valid_phone_number("5551234567")) # True
print(is_valid_phone_number("+44 20 7123 4567")) # True
print(is_valid_phone_number("123")) # False
print(is_valid_phone_number("abc-def-ghi")) # False
How it works: This Python snippet uses a regular expression to validate phone numbers, accommodating various common formats. It allows for an optional international country code, parentheses around the area code, and common separators like hyphens, spaces, or dots. The `fullmatch()` method ensures that the entire string matches the pattern, providing robust validation for user input in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs