Skip to content

Instantly share code, notes, and snippets.

@gliush
Last active August 11, 2017 10:31
Show Gist options
  • Select an option

  • Save gliush/8ddae30931b0a94b8268c7f88fa8df80 to your computer and use it in GitHub Desktop.

Select an option

Save gliush/8ddae30931b0a94b8268c7f88fa8df80 to your computer and use it in GitHub Desktop.
libphonenumber formatter and validator

Script to validate and format phone numbers

To configure environment, run

python3 -m venv ./.venv
source ./.venv/bin/activate
pip3 install -r requirements.txt

Then run

./validity_check.py <phone_number>

Examples:

$ ./validity_check.py 111-111-1111
Not a valid phone number

$ ./validity_check.py 234-567-1111
+12345671111
docopt
-e git://github.com/daviddrysdale/python-phonenumbers.git#egg=python-phonenumbers
#!.venv/bin/python3
"""Phone masking number validator and formatter
Usage:
validity_check.py <phone_number>
Options:
-h --help Show this screen
"""
from docopt import docopt
import sys
from phonenumbers import parse, format_number, is_valid_number, PhoneNumberFormat, phonenumberutil
def main(args):
phone_number = args["<phone_number>"]
x = None
try:
x = parse(phone_number, "US")
valid = is_valid_number(x)
except phonenumberutil.NumberParseException:
valid = False
if valid:
formatted = format_number(x, PhoneNumberFormat.E164)
print(formatted)
else:
print("Not a valid phone number")
sys.exit(1)
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
main(arguments)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment