How to validate an e-mail address - Python

/ #Python


Every now and then, we want to check if an e-mail address is valid. Maybe you're building a user sign up or a newsletter registration form?

Validating an e-mail - example

# Import regex library
import re

# Regex
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'

# Create a simple function
def check(email):  
  if(re.search(regex,email)):  
    return True
  else:
    return False

# Checks

>>> check('codewithstein@gmail.com')
True

>>> check('codewithsteingmail.com')
False

Comments

Brian | Dec 18, 20 04:22

Great example! Thanks!

Stein Ove Helset | Dec 18, 20 01:00

You're welcome Brian :-D

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.