This snippet shows you how to easily validate any email using Python's awesome isValidEmail() function. Validating an email means that you're testing whether or not it's a properly formattedĀ email. While this code doesn't actually test if an email is real or fake, it does make sure that the email entered by the user is in a valid email format (a string of a certain length containing characters followed by an @ symbol followed by characters followed by a "." followed by more characters.

The code for validating is actually pretty simple, and is very similar to the way you'd perform this particular task using any other OOP language. Take a look at the snippet below to see for yourself.

import re
def isValidEmail(email):
 if len(email) > 7:
 if re.match("^.+@([?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email) != None:
 return True
 return False
if isValidEmail("[email protected]") == True :
 print "This is a valid email address"
else:
 print "This is not a valid email address"

This code can be used in any Python project to check whether or not an email is in the proper format. It will need to be modified to be used in as a form validator, but you can definitely use it as a jumping off point if you're looking to validate email addresses for any form submissions.

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

  • http://rizkiaditya24.blogspot.com/ M. Rizki Aditya

    Hi jack, the regex doesnt work for me. So, I use this:
    ^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$

  • Nithin M

    @mradityanod:disqus your solution ignrores case in username part. eg “[email protected]” wont be validated