Tuesday, January 29, 2013

Phone number validation

This is a simple python validation routine for (American) phone numbers. Inputs from a user-specified file are validated according to whitelisting rules that I came up with (see comments), and valid inputs are written to a file. This was a good exercise with regex.



#validation method: whitelisting.
#formula for valid phone number:
# a. "1" (optional)
# b. " " or "-" or "." (optional)
# c. open parenthesis (optional)
# d. 3-digit area code
# e. close parenthesis (optional)
# f. " " or "-" or "." (optional)
# g. 3-digit exchange
# h. " " or "-" or "." (optional)
# i. 4-digit extension

import re
import sys
import os


valid = re.compile('^1?[-. ]?[(]?[0-9]{3}[)]?[-. ]?[0-9]{3}[- .]?[0-9]{4}$')


class Validate:

  def __init__(self):
self.inputfile_name = None
self.inputfile = ""
self.result = None
self.output_file = open(os.path.join(os.getcwd(), "phoneoutput.txt"), 'w')

def load_input_file(self, inputfile_name):
self.inputfile_name = inputfile_name
if os.path.exists(self.inputfile_name):
self.inputfile = open(self.inputfile_name).readlines()
else:
print "File does not exist."
return

def validate(self):
for line in self.inputfile:
self.result = valid.match(line)
if self.result:
self.output_file.write("%s\n" % line)
else:
pass

self.output_file.close()

def execute():
engine = Validate()
if len(sys.argv) != 2:
print "Usage: 'phonevalidate_file.py [filename]'"
exit
if len(sys.argv) == 2:
engine.load_input_file(sys.argv[1])
engine.validate()

execute()

No comments:

Post a Comment