I was doing a programming challenge and the object was to validate an email address, I wrote a simple little email validator and would like some input on how I can make it more efficient.
How it works, it has two validations, one with a regex, and one validating the length (most email addresses are over 12 characters, so that's what I went with).
The regex checks for an
@ and a
. symbol. This is all inside of its own validation class.
import re class Validator(object): def __init__(self, email): self.email = email def check_for_symbol(self): if re.search("[@.]", self.email) is None: return False else: return True def check_length(self): if len(self.email) >= 12: return True else: return False def email_to_verify(): return raw_input('Enter your email address: ') def check_email(email): validator = Validator(email) symbol = validator.check_for_symbol() if symbol is False: print "Your email address is not valid. Failed symbols.." length = validator.check_length() if length is False: print "Your email is not valid. Failed length" if length and symbol is True: print "Email is a valid email address." if __name__ == '__main__': e = email_to_verify() check_email(e)
Is there a way to make this more efficient?
Examples of usage:
C:\challenges>python email_val.py Enter your email address: test Your email is not valid. Failed symbols check. Your email is not valid. Failed length check. C:\challenges>python email_val.py Enter your email address: email@example.com Your email is not valid. Failed length check. C:\challenges>python email_val.py Enter your email address: firstname.lastname@example.org Email is a valid email address.