How to check if a email address is valid or not in Python:
This post will show you how to do email address validation in Python. A email address looks like name@domain.com. For example, your-name@domain.com. Not always your-name is a name. It can be anything that distinguish the person behind that address. For example, admin@domain.com In this post, we will learn two different ways to solve it: By using regex or regular expression and by using a different module.
Using regex:
Using regex, we can use one pattern and match it with a string to find out if it works or not. For regular expression or regex, python provides one inbuilt module re that we can use with a pattern to check if it matches a string or not.
For checking email, I am taking this pattern from this discussion. Below is the complete program :
import re
pattern = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$'
def isValidEmail(email):
if(re.search(pattern, email)):
return True
else:
return False
if __name__ == '__main__':
mail_list = ['hello@domain.com', 'next@me.com', '123.com']
for email in mail_list:
print("{} -> {}".format(email, isValidEmail(email)))
- Here, isValidEmail is a method that takes one string as parameter and checks if it is valid or not using regex re module. re.search checks one string using a pattern. It returns None if matching is failed.
- It returns True or False.
- We are checking three emails stored in the array mail_list.
This program will print the below output:
hello@domain.com -> True
next@me.com -> True
123.com -> False
Using validators module:
validators is a module that provides different types of validations like we can check for url, email etc. For emails, it uses Django’s email validator. Below is the method:
.email(value, whitelist=None)
It validates the email value and whitelist is the domain list that we want to whitelist. For success, it returns True and for failed validation, it throws one ValidationFailure. If we write the above program using validators, it looks as like below :
import validators
def isValidEmail(email):
return validators.email(email)
if __name__ == '__main__':
mail_list = ['hello@domain.com', 'next@me.com', '123.com']
for email in mail_list:
print("{} -> {}".format(email, isValidEmail(email)))
It will print the below output:
hello@domain.com -> True
next@me.com -> True
123.com -> ValidationFailure(func=email, args={'value': '123.com', 'whitelist': None})