This function simply validates an e-mail address. Ignore this recepie and go to my "StringValidator" recepie, which is a much better solution
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
|
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!
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
There's an RFC that describes how to validate emails (RFC 3696). I wrote a Python library that implements that. It's part of Lepl. The documentation is here:
That includes support for IPv6 addresses, for example. The tests at http://www.acooke.org/lepl/api/lepl.apps._test.rfc3696-pysrc.html include many examples that are perfectly valid, but that would be missed by the routines here:
Sorry, I should probably include an example.
To install:
To use:
The above example did not work for me. This is what worked for me
from lepl.apps.rfc3696 import Email
t1 = Email()
Email function does not take an argument, it is just a validator
if t1('valid_email_address@domain.com'): do something
Dang ... I did not know that a hash sign highlights the comments here .. sorry for that.