validate phone numbers in python


If you need to validate phone numbers in python the phonenumbers module is a great library

Installation Instructions

pip install phonenumbers

Example

import phonenumbers

x = phonenumbers.parse("+442083661177", None)
print(x)
type(x)

y = phonenumbers.parse("020 8366 1177", "GB")
print(y)
print(x == y)

# as dialed from GB, not a GB number
z = phonenumbers.parse("00 1 650 253 2222", "GB")
print(z)


z = phonenumbers.parse("+120012301", None)
phonenumbers.is_valid_number(z)
# output
Country Code: 44 National Number: 2083661177
Country Code: 44 National Number: 2083661177
True
Country Code: 1 National Number: 6502532222
False

As you type phone number validation

>>> formatter = phonenumbers.AsYouTypeFormatter("US")
>>> print formatter.input_digit("6")
6
>>> print formatter.input_digit("5")
65
>>> print formatter.input_digit("0")
(650
>>> print formatter.input_digit("2")
(650) 2
>>> print formatter.input_digit("5")
(650) 25
>>> print formatter.input_digit("3")
(650) 253
>>> print formatter.input_digit("2")
650-2532
>>> print formatter.input_digit("2")
(650) 253-22
>>> print formatter.input_digit("2")
(650) 253-222
>>> print formatter.input_digit("2")
(650) 253-2222