Contents
Validate Phone Number
There are two functions in phonenumbers library to validate if the given phone number is a valid one, or check if the given phone number is a possible phone number.
- phonenumbers.is_valid_number() function performs a full validation of a phone number for a region using length and prefix information.
- phonenumbers.is_possible_number() function quickly guesses whether a number is a possible phone number by using only the length information.
You may be wondering why use is_possible_number() function when we have is_valid_number() function. The reason is is_possible_number() is much faster than a full validation by s_valid_number().
And there could be use-cases where there is a requirement only to check if the phone number format is correct, rather than getting into much deeper details.
Examples
1. Check if Phone Number is valid
In the following program, we take a phone number as a string in phonenumber_string, and check if this is a valid phone number using phonenumbers.is_valid_number() function.
Python Program
import phonenumbers
# Take phone number in a string
phonenumber_string = "+442083661177"
# Parse the string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)
# Check if the PhoneNumber is a valid number
if phonenumbers.is_valid_number(x):
print('Given phone number is valid.')
else:
print('Given phone number is not valid.')
Run Code CopyOutput
Given phone number is valid.
2. Check if Phone Number is possible
In the following program, we take a phone number as a string in phonenumber_string, and check if this phone number is possible (acceptable number of digits) using phonenumbers.is_possible_number() function.
Python Program
import phonenumbers
# Take phone number in a string
phonenumber_string = "+442083661177"
# Parse string to a PhoneNumber object
x = phonenumbers.parse(phonenumber_string)
# Check if the PhoneNumber is a possible number
if phonenumbers.is_possible_number(x):
print('Given phone number is possible.')
else:
print('Given phone number is not possible.')
Run Code CopyOutput
Given phone number is possible.
Summary
In this tutorial of Python Examples, we learned how to validate if given phone number in PhoneNumber object is a valid one using phonenumbers library, with the help of example programs.