ActiveState Code

Recipe 65215: E-mail Address Validation


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

  1. 1. At 2:47 p.m. on 18 aug 2001, Anonymous said:

    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

  2. 2. At 10:35 a.m. on 26 mar 2003, Stephen White said:

    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 .

  3. 3. At 9:08 p.m. on 12 sep 2004, Peter Sanchez said:

    .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}$')

  4. 4. At 3:17 a.m. on 20 sep 2005, Shekhar Tiwatne said:

    idn emails. I think this recepie may not validate idn email ids. Try validating user@zääz.de .

  5. 5. At 7:40 a.m. on 4 apr 2008, Rodolfo Puig said:

    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)

  6. 6. At 11:53 p.m. on 18 sep 2008, Timothee Besset said:

    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}$"

  7. 7. At 10:47 a.m. on 6 nov 2008, andreas.mock said:

    Hi all,

    just came across this recipe and read #5. Here is your false positive:

    haha.hoho.@somedomain.de
    

    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