Tuesday, 29 May 2018

Python: Validate Phone Numbers

Phone numbers can be validated very easily using python-phonenumbers.
Here is a short example demonstrating the use of phonenumbers package.  I am using "None" as the country. Any country can be used such as e.g. "GB", "US"
Remember to

pip install phonenumbers
And

import phonenumbers;

def validate_phone(value):
    try:
        parsed_number = phonenumbers.parse(value, None)
        if not phonenumbers.is_valid_number(parsed_number) or 
           not phonenumbers.is_possible_number(parsed_number):
               print("Please provide a valid phone number e.g +CountryCodeNumber")
               return False
    except phonenumbers.phonenumberutil.NumberParseException:
               print("Please provide a valid phone number e.g +CountryCodeNumber")
               return False
 return True

No comments:

Post a Comment