DEV Community

Cover image for How to Validate Emails in Laravel: Quick and Simple Steps
Denys
Denys

Posted on • Originally published at mailtrap.io

How to Validate Emails in Laravel: Quick and Simple Steps

The process of email validation in Laravel is simpler than you might think. By the end of this article, you’ll know how to set up your own email validation system.

First off, let’s clarify something important: email validation focuses solely on the format of the email, meaning how it’s written.

This differs from email verification, which goes beyond format to validate the email’s usage and authenticity. If you’re interested in the step-by-step Laravel email verification, check out our video tutorial:

While you can also perform validation on the client side, such as in a Laravel contact form, in this article, I’ll strictly focus on server-side techniques.

Laravel email validation rule

In Laravel, I use a robust validation system that simplifies workflows and ensures data integrity. My go-to tools are Laravel’s Validator facade and Form request classes, which handle data validation effectively.

These tools ensure that data meets predefined criteria before processing, helping maintain quality and consistency.

Using Validator facade

Using the Validator facade directly within your controllers allows quick, inline validation, making it ideal for simpler or less frequent validation scenarios.

****_Note: The code examples in this article are based on Laravel 10. While many of these techniques will be applicable to other versions, some specifics may differ. _

To use the Validator facade, follow these steps:

  1. Import the Validator

Add the Validator facade at the beginning of your controller file to enable Laravel’s built-in validation features.

use Illuminate\Support\Facades\Validator;
Enter fullscreen mode Exit fullscreen mode

This will allow you to access Laravel’s built-in validation features directly within your controller.

  1. Create Validation Rules

Define specific validation rules for the data you process within your controller method.

$rules = [
    'email' => 'required|email',
    'name' => 'required|string|max:255',
];
Enter fullscreen mode Exit fullscreen mode

These rules determine what data is acceptable, ensuring that your application only processes correctly formatted data.

  1. Apply Validation

Apply the defined rules to the incoming data using the Validator facade.

$validator = Validator::make($request->all(), $rules);
Enter fullscreen mode Exit fullscreen mode

This code will check the validity of the data against your predefined rules.

  1. Handle Validation Failure

Lastly, determine the response if the validation fails.

if ($validator->fails()) {
    return redirect('form')->withErrors($validator)->withInput();
}
Enter fullscreen mode Exit fullscreen mode

This will redirect users to the form with error messages and their data, helping them correct inputs.

Using Form Request Classes

Laravel’s form request classes help keep your controller code clean by separating the validation logic into dedicated classes.

Here are the steps to effectively use them for email validation:

  1. Generate a Form Request Class

Using Laravel’s Artisan command line tool, create a new form request class:

php artisan make:request EmailValidationRequest
Enter fullscreen mode Exit fullscreen mode

This command generates a new class in the App_Http__Requests_ directory, a PHP file where you can define all your custom validation rules.

  1. Define Validation Rules in the Request Class

Open your newly created EmailValidationRequest class to add your own validation rules.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class EmailValidationRequest extends FormRequest
{
    public function authorize()
    {
        return true; // Always return true unless you have specific authorization logic
    }

    public function rules()
    {
        return [
            'email' => 'required|email',
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

This method requires the email field to be valid, ensuring data adheres to rules for consistent and maintainable validation checks.

  1. Apply the Request Class in Your Controller

Lastly, incorporate the EmailValidationRequest in your controller method.

public function store(EmailValidationRequest $request)
Enter fullscreen mode Exit fullscreen mode

This automates validation, redirecting with errors on failure and keeping your controller focused on core logic.

Regular expression for email validation in Laravel

When working with Laravel, the standard email validation rule, which primarily checks for a valid email format, doesn’t fit every scenario.

For instance, it’s unsuitable when you exclude emails from disposable domains that are technically valid but not desired for a user registration process.

This is why I rely on regular expressions (regex), a flexible alternative that offers customized validation and deals with complex scenarios.

Creating an effective regex means knowing which patterns to include or exclude to ensure it’s flexible and lenient. Here’s an example of a regex pattern:

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Enter fullscreen mode Exit fullscreen mode

This pattern checks for:

  • A start with one or more alphanumeric characters, including dots, underscores, and percent, plus, & minus signs.
  • An @ symbol.
  • A domain name consisting of one or more alphanumeric characters, including hyphens and dots.
  • A domain extension of at least two alphabetic characters.

To add a custom regex to Laravel’s validation system, directly include it in the controller’s rules array:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

public function store(Request $request)
{
    $rules = [
        'email' => ['required', 'regex:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'],
    ];

    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        return back()->withErrors($validator)->withInput();
    }

    // Email is valid, proceed with the next steps
}
Enter fullscreen mode Exit fullscreen mode

This setup ensures that the input email adheres strictly to the defined regex pattern, embedding it into the validation rules for robust control over email formats unique to your application’s needs.

Email validation in Laravel using API

Standard validation rules, custom regular expressions, and regex are great, but API-based solutions are sometimes the right way to achieve the highest accuracy and security.

There are several services available, such as Hunter, ZeroBounce, and NeverBounce, which offer APIs to perform advanced email checks.

Such API-based validation is helpful when you need real-time, comprehensive checks and especially useful when:

  • Confirming domain authenticity to prevent emails from unauthorized or spoofed domains.
  • Verifying that an email address is not only valid but also active.
  • Enhancing security by ensuring that only valid email addresses are allowed.

To demonstrate how to integrate API-based email validation into your Laravel applications, I’ll use ZeroBounce, a tool that I found helpful for such cases.

  1. Sign Up

Register an account at ZeroBounce, then locate and copy your API key from the dashboard.

  1. C*onfigure API Key*

Add the API key to your .env file for security.

ZEROBOUNCE_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode
  1. Set Up HTTP Client

Implement the HTTP client to send requests to the ZeroBounce API.

use Illuminate\Support\Facades\Http;

public function validateEmailWithZeroBounce($email)
{
    $apiKey = env('ZEROBOUNCE_API_KEY');
    $response = Http::get("https://api.zerobounce.net/v2/validate?api_key={$apiKey}&email={$email}");

    return $response->json();
}
Enter fullscreen mode Exit fullscreen mode

This function sends a GET request to ZeroBounce, which checks the email address for validity and deliverability, returning a JSON response.

  1. Utilize the Validation Function

Use the validation function in your web application to check if emails are valid.

public function registerNewUser(Request $request)
{
    $emailCheck = $this->validateEmailWithZeroBounce($request->email);

    if ($emailCheck['status'] == 'valid' && $emailCheck['smtp_valid'] == true) {
        // Proceed with user registration
    } else {
        return back()->withErrors(['email' => 'Invalid or non-deliverable email address.']);
    }
}
Enter fullscreen mode Exit fullscreen mode

This validation method uses the ZeroBounce API response to determine whether to proceed with a new user registration based on the email’s validity and deliverability.

Email validation in Laravel using the email-validator library

In Laravel, you can easily implement email validation using the egulias/EmailValidator library. Here’s a brief guide on how to do it:

  1. Install the Library

First, you need to install the egulias/EmailValidator library via Composer.

Open your terminal, navigate to your Laravel project directory, and run the following command:

Once the library is installed, you can use it in your Laravel application for email validation within the controller or form request validation.

  1. Controller Validation

In your controller, use the validate method provided by Laravel to validate the email input against the egulias/EmailValidator library. Here’s an example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Egulias\EmailValidator\Validation\EmailValidation;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email', function ($attribute, $value, $fail) {
                $validator = new EmailValidation();
                if (!$validator->isValid($value)) {
                    $fail('The '.$attribute.' is invalid.');
                }
            }],
        ]);

        // Process valid email
    }
}
Enter fullscreen mode Exit fullscreen mode

This snippet validates email addresses using a custom rule, utilizing a closure with the isValid method from the egulias/EmailValidator library.

Using Form Request Validation

Alternatively, you can create a custom form request and define the email validation rules there.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Egulias\EmailValidator\Validation\EmailValidation;

class StoreUserRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'email' => ['required', 'email', function ($attribute, $value, $fail) {
                $validator = new EmailValidation();
                if (!$validator->isValid($value)) {
                    $fail('The '.$attribute.' is invalid.');
                }
            }],
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, in your controller, type-hint the custom form request:

use App\Http\Requests\StoreUserRequest;

public function store(StoreUserRequest $request)
{
    // Process valid email
}
Enter fullscreen mode Exit fullscreen mode

Email validation as a part of email testing

A solid validation mechanism is, without a doubt, a must for well-maintained email contacts and improving overall deliverability.

However, it’s not enough if you’re not testing your emails before sending them. This step is crucial for your emails to land where they should—right in your recipients’ inboxes… Besides, we all aim for high deliverability rates.

This is why I always find myself relying on Mailtrap Email Testing—a part of the more extensive Mailtrap Email Delivery Platform.

Mailtrap Email Testing allows you to review and troubleshoot emails across staging, development, and QA environments without cluttering your recipients’ inboxes. You can also check the support for HTML and CSS templates with the most popular mailbox providers.

Image description

Test Emails with Mailtrap for Free

Furthermore, it also enables you to assess the Spam Scores of your emails and check whether your IP is listed on any blacklists.

Image description

Additionally, you can create, edit, and test your HTML email templates and then switch to the production environment when you’re ready to send.

Image description

You can further streamline your testing process by leveraging Mailtrap’s Email Testing API. This will help identify and resolve code issues early and ensure that your emails are perfect when they are sent.

This is merely a snapshot of what Mailtrap Email Testing is capable of. Check out the video below for a more detailed exploration of its features. And, of course, try the tool yourself to let its performance do the talking.

How Mailtrap Email Testing Works – Getting Started Guide

Summing up

Email validation in Laravel is crucial for anyone who wants to build a reliable and effective email communication system. From simple Laravel validation rules to more sophisticated API checks, I encourage you to try all these methods to discover which suits your needs best.

Experimenting with these techniques and incorporating Mailtrap’s Email Testing into your workflow can significantly enhance your email delivery success.

For those eager to master the art of email management with Laravel, explore our articles on the topic, which are designed to broaden your understanding and enhance your skills! 😉

We appreciate you chose this article to know about Laravel email validation. If you want to find more interesting content on related topics, follow Mailtrap blog!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.