This function simply validates an e-mail address. Ignore this recepie and go to my "StringValidator" recepie, which is a much better solution
| Python |
1 2 3 4 5 6 7 8 | import re
def validateEmail(email):
if len(email) > 7:
if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
return 1
return 0
|
Discussion
E-mail address validation is a pretty common thing when dealing with web forms. The reason I check if the length of "email" is greater than 7 is because to the best of my knowledge, no address can be shorter than 7 characters (ie. j@jj.ca).
See my "StringValidator" recepie for a much better solution!


Comments
Short email adresses. It is important to note that email adresses _can_ be shorter than 7 characters. Although domain names shorter than 2 letters are not allowed in .com .net and .org, many ISO country domain registrars do allow one letter domain names. For example in Denmark, where I live. For example see http://www.n.dk
Short email addresses and .va. If you'll do 'nslookup -type=mx va' or similar you'll find that va has mail exchangers associated. This means that the shortest email address, IMHO, is .
.info? Doesn't look like your code will validate .info domains. Here is the regexp I use for my email validation:
re.compile('^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$')
idn emails. I think this recepie may not validate idn email ids. Try validating user@zääz.de .
Production Code. I've been using this regular expression for many years in various production environments (affiliate systems, forums, etc) and it hasn't given me any false positives. Enjoy...
re.match("^[a-zA-Z0-9._%-]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email_str)
that one in #5 will not accept john+doe@ and john-doe@
I've modified it into:
"^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$"
Hi all,
just came across this recipe and read #5. Here is your false positive:
is not a valid e-mail address. But the regex gives no false. Dots at the start and at the end of the local part are not allowed. See RFC2822.
Best regards
Andreas Mock
Sign in to comment