Python Code to Validate an Email Address
Many programs ask for an email address, like a sign up or a contact form. Before saving it, you should check that it looks like a real email. In Python this is easy with the re module (regular expressions).
Python function to validate an email
import re
pattern = r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
def is_valid_email(email):
return re.match(pattern, email) is not None
tests = [
"robin@example.com",
"robin@example",
"robin.kumar+test@mail.co.in",
"robin@@example.com",
"@example.com",
]
for email in tests:
print(email, "->", is_valid_email(email))
Output:
Tutorials Class - Output Window
robin@example.com -> True
robin@example -> False
robin.kumar+test@mail.co.in -> True
robin@@example.com -> False
@example.com -> False
How the pattern works
| Part | Meaning |
|---|---|
^ and $ | Match the whole text, from the start to the end |
[A-Za-z0-9._%+-]+ | One or more letters, digits or these symbols before the @ |
@ | Exactly one @ sign |
[A-Za-z0-9.-]+ | The domain name, like example or mail.co |
\.[A-Za-z]{2,} | A dot and an ending of at least 2 letters, like .com or .in |
Note:
This is a simple check of the format. It cannot tell if the mailbox really exists. To be sure, send a confirmation email with a link.
Related: Python Modules, Python Strings.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |