Hey guys, in this tutorial I will show you at least 3 ways to validate an email in Python. Validate here means to check if an email is valid or not.
We will be using RegEx and 2 libraries: email_validator and flanker.
Let's go!
Check if Email is Valid using RegEx
Similar to the URLs, emails also have a common pattern that can be expressed using RegEx.
Take a look at those examples:
dminhvu.work@gmail.com
dminhvu+abc@gmail.com
minhvdse000@fpt.edu.vn
The common point is:
- Starts with a string of characters, which is your username.
- Followed by an
@
symbol. - Followed by a domain name, e.g.
gmail.com
,fpt.edu.vn
, etc.
So, we can use the following RegEx to validate an email:
import re def validate_email(email): pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" return re.match(pattern, email) print(validate_email("dminhvu")) # None print(validate_email("dminhvu.work@gmail.com")) # <re.Match object; span=(0, 24), match='dminhvu.work@gmail.com'> print(validate_email("dminhvu+abc@gmail.com")) # <re.Match object; span=(0, 21), match='dminhvu+abc@gmail.com'> print(validate_email("minhvdse000@fpt.edu.vn")) # <re.Match object; span=(0, 24), match='minhvdse000@fpt.edu.vn'>
You can run it using python3 validate_email.py
command.
