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:
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:
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:
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
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.
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.
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.
Examine the API Response
Call the function using the Django shell. Pass it a test email. The response should look something like this.
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.
Now, we can add this function as a step in the validate_email function.
Now, we can pass the validate_email function as a validator to the validators array on the email field in our models file.
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.