0
0
PythonHow-ToBeginner · 3 min read

How to Validate Phone Number Using Python: Simple Guide

You can validate a phone number in Python using the re module with a regular expression pattern to check the format, or use the phonenumbers library for more accurate and international validation. The phonenumbers library parses, formats, and validates phone numbers easily.
📐

Syntax

To validate phone numbers using regular expressions, you use the re.match() function with a pattern that describes valid phone number formats. For more robust validation, the phonenumbers library provides functions like parse() and is_valid_number().

  • re.match(pattern, string): Checks if the string matches the pattern from the start.
  • phonenumbers.parse(number, region): Parses the number with a region code.
  • phonenumbers.is_valid_number(parsed_number): Returns True if the number is valid.
python
import re

# Regex pattern example for US phone numbers
pattern = r"^\+?1?\s?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"

# Using phonenumbers library
import phonenumbers

# Parse and validate
parsed_number = phonenumbers.parse("+14155552671", "US")
is_valid = phonenumbers.is_valid_number(parsed_number)
💻

Example

This example shows how to validate a phone number using both a regular expression and the phonenumbers library. It prints whether the number is valid or not.

python
import re
import phonenumbers

def validate_phone_regex(phone):
    pattern = r"^\+?1?\s?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"
    return bool(re.match(pattern, phone))

def validate_phone_phonenumbers(phone, region="US"):
    try:
        parsed = phonenumbers.parse(phone, region)
        return phonenumbers.is_valid_number(parsed)
    except phonenumbers.NumberParseException:
        return False

phone1 = "+1 415-555-2671"
phone2 = "12345"

print(f"Regex validation for {phone1}:", validate_phone_regex(phone1))
print(f"Regex validation for {phone2}:", validate_phone_regex(phone2))
print(f"Phonenumbers validation for {phone1}:", validate_phone_phonenumbers(phone1))
print(f"Phonenumbers validation for {phone2}:", validate_phone_phonenumbers(phone2))
Output
Regex validation for +1 415-555-2671: True Regex validation for 12345: False Phonenumbers validation for +1 415-555-2671: True Phonenumbers validation for 12345: False
⚠️

Common Pitfalls

Common mistakes when validating phone numbers include:

  • Using too simple regular expressions that don't cover international formats.
  • Not handling exceptions when parsing numbers with phonenumbers.
  • Assuming all phone numbers have the same length or format.
  • Ignoring country codes which can cause false negatives.

Always test with multiple formats and consider using phonenumbers for better accuracy.

python
import re

# Wrong: too simple regex that misses valid formats
simple_pattern = r"^\d{10}$"

print(re.match(simple_pattern, "+14155552671"))  # None, fails to match

# Right: use a more flexible regex or phonenumbers library
import phonenumbers
try:
    num = phonenumbers.parse("+14155552671", "US")
    print(phonenumbers.is_valid_number(num))  # True
except phonenumbers.NumberParseException:
    print(False)
Output
None True
📊

Quick Reference

Tips for phone number validation in Python:

  • Use re for simple format checks.
  • Use phonenumbers for international and detailed validation.
  • Always handle exceptions when parsing numbers.
  • Test with various real-world phone number formats.

Key Takeaways

Use the phonenumbers library for accurate and international phone number validation.
Regular expressions can validate simple formats but may miss complex or international numbers.
Always handle exceptions when parsing phone numbers to avoid crashes.
Test your validation with different phone number formats to ensure reliability.