The Simple Way to Validate Phone Numbers in Python

Last Updated Jan 31, 2022
Emma Jagger

Engineer, maker, Google alumna, CMU grad

Table of Contents:

Phone number validation can be very challenging. The phone number formats variy with different countries. Some of them share the same country code. For example, a valid number starts with +1, the country code of the USA, Canada, and Caribbean islands. This helps to avoid an invalid default region. The phone number formats can even vary within the same country. Overall, there are a lot of complexities. It can make validating international phone numbers very challenging and you might come across a validating phone numbers problem. Is there any way to validate phone number Python effortlessly? In this post, you will find all the details.

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

How to validate a phone number in Python

You can validate country codes of phone numbers with Regex. However, it is not an efficient solution. You don’t want to create a custom Regex for each of the countries. It will make the process very complex. Fortunately, there is a library that helps you to validate phone numbers in Python easily. It is known as Python Phonenumbers. In this post, you will find the details of using this Python phone number validator to verify phone numbers. Also, you will find the process of getting user-specific geolocation data. If you want to dive into other Python guides, make sure to read about geolocation an IP address in Python or how to validate emails using Python.

Validate with Python PhoneNumbers

You can validate phone numbers with the Python library Phonenumbers using two different methods. Let’s take a look at how we can use the Phone numbers solution.

Validate Phone Number Using the is_possible_number() Method:

1. First, you have to import the phonenumbers library.


import phonenumbers

2. Create a variable, called string_phone_number. It will contain your ten digit number.


string_phone_number = "+40032215789"

3. Then you need to parse the given phone number.


phone_number = phonenumbers.parse(string_phone_number)

4. Finally, you have to use the is_possible_number() method to perform the validation. Then you can set up the print output.


print(phonenumbers.is_possible_number(phone_number))

Overall, the code will look like this:


import phonenumbers

my_string_number = "+40021234567"
my_number = phonenumbers.parse(my_string_number)
print(phonenumbers.is_possible_number(my_number))

You will get this output:


True

Validate Phone Number Using the is_valid_number() Method:

1. Import the phonenumbers library.


import phonenumbers

2. Create the string_phone_number variable. It will contain your phone number.


string_phone_number = "+40032215789"

3. Then you have to parse the string_phone_number.


phone_number = phonenumbers.parse(string_phone_number)

4. Now, you can utilize the is_valid_number() method to start validating phone number


print(phonenumbers.is_valid_number(my_number))

Overall, the code will look like this with the phonenumber object:


import phonenumbers

my_string_number = "+40021234567"
my_number = phonenumbers.parse(my_string_number)
print(phonenumbers.is_valid_number(my_number))

You will get this output:


True

The Problem with the Two Methods:

As you can see, the only challenge with the above code is the two different results by using the same number. The is_possible_number() method provides False output. But the is_valid_number() method gives you True. What’s the reason behind the difference?

is_possible_number() method verifies the phone number by checking the length of the parsed number. On the other hand, is_valid_number() method looks for the length, phone number prefix, and region to perform a complete validation.

As is_valid_number() method performs full validation, it is a bit slower in delivering the result. So, while iterating over a large list of phone numbers, you can consider using the is_possible_number() method. It will provide results faster. But as you can see in the code examples, the results may not always be right. There is a limitation with the accuracy.

How can you fix the issue? You can try using an API, like Abstract’s Phone Validation API, to validate phone numbers without worrying about the accuracy. You will find the details later in this post.

Getting location from Phone numbers in Python

A phone number is loaded with a variety of information, including user-specific geolocation data. You can use the data to send promotional notifications at the right time in terms of the customer’s time zone. You don’t want to notify the people in the middle of the night. Just pay close attention to formatting phone numbers.

How to Extract Geolocation from the Phone Number in Python

1. First, you have to import phonenumbers library and timezone.


import phonenumbers
from phonenumbers import timezone

2. Then you have to parse your phone number.


phone_number = phonenumbers.parse("+447986123456")

3. Now, you can print the result.


print(timezone.time_zones_for_number(phone_number))

Overall, the code will look like this:


import phonenumbers
from phonenumbers import timezone

phone_number = phonenumbers.parse("+447986123456")
print(timezone.time_zones_for_number(phone_number))

You will get this output:


('Europe/Guernsey', 'Europe/Isle_of_Man', 'Europe/Jersey', 'Europe/London')

How to Extract Carrier Name from the Phone Number in Python

You might want to group your phone numbers by their carrier. It will have an impact on your product cost. The Phonenumbers library deals with very easy to extract the name of the carrier from a valid mobile number. You just need to follow these steps:

1. Import phonenumbers library and timezone.


import phonenumbers
from phonenumbers import timezone

2. Now, you have to parse the phone number.


phone_number = phonenumbers.parse("+40721234567")

3. Finally, you have to use the carrier.name_for_number() method to get the carrier’s name of the given phone number.


print(carrier.name_for_number(phone_number, "en"))

Overall, the code will look like this:


import phonenumbers
from phonenumbers import carrier

phone_number = phonenumbers.parse("+40721234567")
print(carrier.name_for_number(phone_number, "en"))

You will get this output:


Vodafone

The Limitation of Extracting Carrier Names with Phonenumbers library

As you can see, the Phonenumbers library has made it very easy for you to extract the name of the carrier. However, there is an issue. In most cases, the Phonenumbers library will be able to provide the name of the carrier accurately for international numbers. However, the result may not be 100% accurate all the time.

Using an API to validate phone numbers

APIs can make the process of validating phone numbers very simple. They enable you to get the job done with just a few lines of code. Also, they help you to extract important data, including carrier, country name, and timezone, with greater accuracy.

You can consider using Abstract’s Phone Validation API. It is lightweight and super-fast. It can help you to determine the validity of phone numbers in 190 countries. It’s very easy to use. You just need to submit the API key and phone number. The Phone Validation API will perform the verification instantly. Also, it provides you with additional data with greater accuracy, including carrier name, line type, city, country, and region.

Let’s try verifying this phone number with Abstract’s Phone Validation API: 14154582468.


https://phonevalidation.abstractapi.com/v1/
	? api_key = YOUR_UNIQUE_API_KEY
	& number = 14154582468

If the request is successful, you will get this response in JSON format:


{
  "number": "14154582468",
  "is_valid_number": true,
  "local_format":"4154582468",
  "international_format": "+14154582468",
  "country_name": "United States of America",
  "country_code": "US",
  "country_prefix":"+1",
  "registered_location": "San Francisco, CA",
  "carrier":"Verizon USA",
  "line_type": "Mobile",
}

Notice that "is_valid_number" is set to true, meaning that we entered one of the valid mobile numbers. That means the given phone number is valid. Also, you get a variety of useful data, like country name, registered location, carrier, etc. Just make sure to format phone numbers correctly.

As you can see, the Abstract’s Phone Validation API has made the verification process very simple. It doesn’t require you to write any code from scratch. You just need to get the API key and make a request for verifying the phone number. There is no complexity. You will get the phone number validated instantly.

Wrapping Up

Now, you have learned different methods for validating phone numbers. You can use the Python Phonenumbers library. However, the easiest way is using Abstract’s Phone Validation API. It can help you perform the verification quickly and effortlessly.

Validate international phone numbers using Abstract's API.

Get started for free
Validate international phone numbers using Abstract's API.
Get started