How to validate a Phone Number in Python

Phone number inaccuracies can lead to all sorts of problems, which I don’t need to go into here. To combat this occurrence, we are going to set up a phone number validation system to assist us in weeding out potential problems. For the easiest possible setup, we will be using an API to evaluate phone number syntax for us. First we are going to set that up with a command for pip install:

pip install cloudmersive-validate-api-client

Now to get our API up and running. This will need an API instance, which can then take in an API key and allow us to call the function that we will use.

from __future__ import print_functionimport timeimport cloudmersive_validate_api_clientfrom import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_validate_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_validate_api_client.PhoneNumberApi(cloudmersive_validate_api_client.ApiClient(configuration))value = cloudmersive_validate_api_client.PhoneNumberValidateRequest() # PhoneNumberValidateRequest | Phone number to validate in a PhoneNumberValidateRequest object.  Try a phone number such as \"1.800.463.3339\", and either leave DefaultCountryCode blank or use \"US\".try:# Validate phone number (basic)api_response = api_instance.phone_number_syntax_only(value)pprint(api_response)except ApiException as e:print("Exception when calling PhoneNumberApi->phone_number_syntax_only: %s\n" % e)

Now enter in a phone number as part of the request object, optionally entering in the DefaultCountryCode, and give it a quick test. And that’s a wrap!

Image for post

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store