Guides
Last updated
August 3, 2023

Email Address Regex Django

Elizabeth (Lizzie) Shipton

Table of Contents:

Get your free
Email Validation
API key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

Validating emails is one of the most useful and basic dev skills. There are many reasons you may need to validate email addresses in a Django app. Email addresses are used for user authentication and are your primary means of communicating with your customers.

One of the most commonly asked questions when it comes to email validation is whether a Regex pattern can be used to validate an email address. While a regular expressions are useful for many things, they are not robust enough to rely on for validating email addresses in a production app.

In this tutorial, we'll look at email address validation with Regex and Django. We'll also take a look at a more robust method for finding a valid e mail address, using a dedicated third-party email address API.

This tutorial assumes you already know how to set up a Django project, Django models, and a Python virtual environment, if you need it. If you don't know how to do those things, check out this tutorial.

Let’s send your first free
Email Validation
call
See why the best developers build on Abstract
Get your free api

Validate Email Address With Regex

Email address validation with Regex requires writing a regular expression that matches a valid email address and then comparing incoming email addresses with that regular expression.

The regex for matching email addresses can get complicated. In fact, there is no "fool-proof" regular expression that matches 100% of valid email addresses.

There is an official standard called RFC 5322 that dictates what valid email addresses should look like. The regular expression for that looks like this:



\A(?:[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*
| "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]
| \\[\x01-\x09\x0b\x0c\x0e-\x7f])*")
@ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
| \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:
(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]
| \\[\x01-\x09\x0b\x0c\x0e-\x7f])+)

It's very complicated, as you can see. For the purposes of this tutorial, we'll use a simpler regular expression. The following is a pretty good Regex pattern for email addresses:



/^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$/gm

Use a Regular Expression in a Validation Function

Once we have a regular expression that approximates a valid email, we need to write a function that uses the pattern. The easiest way to use regular expressions in Python is to import the re module, which provides methods for creating and using regular expressions.

That function might look something like this:



def validate_email_address(email_address):
if not re.search(r"^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$", email_address):
print(f"The email address {email_address} is not valid")
return False

The re.search module takes two arguments: a regex and a string to examine. It searches the entire string and returns True if a substring that matches the pattern is found anywhere in the string.

Because re.search returns a boolean value, the above function could also be written as



def validate_email_address(email_address):

return re.search(r"^[A-Za-z0-9_!#$%&'*+\/=?`{|}~^.-]+@[A-Za-z0-9.-]+$", email_address)

Validate Email Address With Validators

A slightly more robust way of validating email syntax is to use built-in Django validators. Validators are HTML5 input attributes such as required, minLength, maxLength, etc.

You can add these validators to your models to do model validation.



from django import forms
from django.core import validators

# email form

class SignUp(forms.Form):
first_name = forms.CharField(initial = 'First Name', required=True)
email = forms.EmailField(initial = 'Enter your email', required=True, validators=[validators.EmailValidator(message="Invalid Email")])

This is a basic Django form with two form fields: first name and email. We've added the required field to both inputs, and added out-of-the-box validation by importing the Django validators module.

The validators.EmailValidator function takes a custom message that will be displayed as an error message to the user as its input. It runs an internal email validator against anything entered into the input and displays the custom message if the email is found to be and invalid email.

Validate Email Address With an API Call

We can also define our own custom validation functions to use with the validators module. Instead of passing a generic method to the validators array, we can write our own method and pass that.

Let's take a look at how to use the AbstractAPI Free Email Validation endpoint to do robust, thorough email validation in Django.

Acquire an API Key

You'll need an API key before you can make requests to the endpoint. Go to the AbstractAPI Free Email Validation API homepage and click "Get Started."

If you've never used AbstractAPI before, you'll be asked to sign up with your email address and password. Once you’ve signed up and logged in, you’ll land on the API’s dashboard, where you’ll see your API key.

Send a Validation Request to the API

We'll us the Python requests module to make our API request. You'll need your API key and the AbstractAPI URL, which you can find on your API dashboard. Create variables for them in your Django model file.



api_key = 'YOUR_API_KEY';
api_url = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + api_key

Next, write a function called validate_email that accepts an email address as an argument and sends it to the API. For now, we'll just print the response.



import requests
api_key = 'YOUR_API_KEY';
api_url = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + api_key

validate_email(email):
response = requests.get(api_url + "&email=email")
print(response.content)

Examine the API Response

Call the function using the Django shell. Pass it a test email. The response should look something like this.



{
"email": "email@domain.com",
"autocorrect": "",
"deliverability": "DELIVERABLE",
"quality_score": "0.80",
"is_valid_format": {
"value": true,
"text": "TRUE"
},
"is_free_email": {
"value": false,
"text": "FALSE"
},
"is_disposable_email": {
"value": false,
"text": "FALSE"
},
"is_role_email": {
"value": false,
"text": "FALSE"
},
"is_catchall_email": {
"value": true,
"text": "TRUE"
},
"is_mx_found": {
"value": true,
"text": "TRUE"
},
"is_smtp_valid": {
"value": true,
"text": "TRUE"
}
}

There are many fields here that tell us if the email is valid or not. Ideally, we should use all these fields to determine the validity of the email address. Write a function that looks at all the fields and returns True if the email is valid, and False if not.



is_valid_email(data):
if data.is_valid_format.value && is_mx_found && is_smtp_valid:
if not is_catchall_email && not is_role_email && not is_free_email:
return true
return false

Now, we can add this function as a step in the validate_email function.



validate_email(email):
response = requests.get(api_url + "&email=email")
is_valid = is_valid_email(response.content)
if not is_valid:
raise forms.ValidationError("Not a valid email")

Now, we can pass the validate_email function as a validator to the validators array on the email field in our models file.



from django import forms
from django.core import validators
import requests

# signup form

api_key = 'YOUR_API_KEY';
api_url = 'https://emailvalidation.abstractapi.com/v1/?api_key=' + api_key

is_valid_email(data):
if data.is_valid_format.value && is_mx_found && is_smtp_valid:
if not is_catchall_email && not is_role_email && not is_free_email:
return true
return false


validate_email(email):
response = requests.get(api_url + "&email=email")
is_valid = is_valid_email(response.content)
if not is_valid:
raise forms.ValidationError("Not a valid email")


class SignUp(forms.Form):
first_name = forms.CharField(initial = 'First Name', required=True)
email = forms.EmailField(initial = 'Enter your email', required=True, validators=[validate_email])

This will send anything input into the EmailField to AbstractAPI for validation. We receive the response and determine if the email is valid. If it is not a valid email, Django shows our custom error message to the user.

Conclusion

In this tutorial, we looked at several methods of validating email addresses using Django models. We first looked at regular expressions, which are not robust enough to rely on in a production app. We then looked at validators found on HTML5 forms, which can be accessed in Django via the validators module. Finally, we wrote our own custom function using a dedicated third-party email validator API.

FAQs

How do you write a regex for an email address in Python?

There are no regular expressions that are 100% foolproof when it comes to validating email addresses. The closest pattern is the RFC 5322 standard, which is a long and complex expression. It looks like this:

\A(?:[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*| "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]| \\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?| \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]| \\[\x01-\x09\x0b\x0c\x0e-\x7f])+)

Some other examples of regular expressions that can be used to validate emails can be found on google.

How can I check if an email address is valid in Django?

Django provides several validation methods for checking email address validity. The easiest way is to import the validate_email method from the core validators module. This is a standalone function that can be used in any models, forms, or views.

How do you validate an email address in Python?

There are many ways to validate an email address in Python. One method is to use a regular expression to match the email syntax. This is not recommended as finding a single pattern that captures all valid emails is challenging. Next, you could use a Python library like email-validator or py3-validate-email. Finally, you could use a third-party API that specifically handles email validation.

Elizabeth (Lizzie) Shipton

Lizzie Shipton is an adept Full Stack Developer, skilled in JavaScript, React, Node.js, and GraphQL, with a talent for creating scalable, seamless web applications. Her expertise spans both frontend and backend development, ensuring innovative and efficient solutions.

Get your free
Email Validation
key now
See why the best developers build on Abstract
get started for free

Related Articles

Get your free
Email Validation
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required