Python: 3 Ways to Validate Phone Numbers

Updated: May 31, 2023 By: Khue Post a comment

Using the phonenumbers library (recommended)

The most convenient and reliable way to validate a phone number in Python is to use the phonenumbers library. It can handle various phone number formats and regions (including international formats).

In general, the steps to check if a phone number is valid with phonenumbers are as follows:

  1. Install the library by running pip install phonenumbers
  2. Import the library into your Python code
  3. Use the parse() and is_valid_number() functions to parse and validate the phone number

Example:

import phonenumbers

# Input a phone number
phone_number = input("Enter a phone number to validate: ")

# Parse the phone number
parsed_number = phonenumbers.parse(phone_number)

# Check if the number is valid
if phonenumbers.is_valid_number(parsed_number):
    print("Valid phone number")
else:
    print("Invalid phone number")

The code will ask you to enter a phone number and then print whether it is valid or not. It’s recommended to enter your country code. If you don’t, the library will assume that the number is from your default region.

Using regular expressions

This approach doesn’t rely on a third-party library, but you’ll have to define a regular expression pattern to validate phone numbers. If you’re new to Python, this task isn’t easy and error-prone.

In the example to come, we’ll use this pattern to match a phone number in the format ddd-ddd-dddd:

pattern = re.compile(r"^\d{3}-\d{3}-\d{4}$")

The pattern means that the string must start with three digits, followed by a dash, followed by another three digits, followed by another dash, followed by four digits, and end there. The re module in Python provides functions to work with regular expressions. You can use the match() function to check if a string matches a pattern.

Example:

import re

# Input a phone number
phone_number = input("Enter a phone number to validate: ")

# Define the pattern
pattern = re.compile(r"^\d{3}-\d{3}-\d{4}$")

# Check if the number matches the pattern
if pattern.match(phone_number):
    print("Valid phone number")
else:
    print("Invalid phone number")

Phone number formats are numerous, including area and international codes, spaces, dashes, and possibly parentheses. If you are building a large project and have to validate a wide range of phone number formats, it is better to use the preceding method.

Using built-in string methods

String methods are functions that can manipulate or check strings based on certain criteria. For example, you can use the isalnum() method to check if a character is a letter or a digit. You can also use indexing and slicing to access parts of a string.

The code example below will validate US phone numbers in a specific format (ddd-ddd-dddd):

# Input a phone number
phone_number = input("Enter a phone number to validate: ")

# Check the length of the string
if len(phone_number) != 12:
    print("Invalid phone number")
else:
    # Check the first three characters
    if not phone_number[:3].isalnum():
        print("Invalid phone number")
    else:
        # Check the fourth character
        if phone_number[3] != "-":
            print("Invalid phone number")
        else:
            # Check the next three characters
            if not phone_number[4:7].isalnum():
                print("Invalid phone number")
            else:
                # Check the eighth character
                if phone_number[7] != "-":
                    print("Invalid phone number")
                else:
                    # Check the last four characters
                    if not phone_number[8:].isalnum():
                        print("Invalid phone number")
                    else:
                        # All checks passed
                        print("Valid phone number")

If you enter 123-456-7890, the output will be Valid phone number.

This approach has some limitations. It is very verbose and repetitive. It cannot handle international numbers, different separators, extensions, etc. You would need to write more conditional statements to handle those cases.