How to Validate Emails in Laravel: Quick and Simple Steps
Published: 2024-05-15 06:42:27

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](https://mailtrap.io/blog/laravel-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:
{% embed https://youtu.be/KiHzbVsErNo %}

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;
```
This will allow you to access Laravel’s built-in validation features directly within your controller.

2. **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',
];
```
These rules determine what data is acceptable, ensuring that your application only processes correctly formatted data.

3. **Apply Validation**

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

```
$validator = Validator::make($request->all(), $rules);
```
This code will check the validity of the data against your predefined rules.

4. **Handle Validation Failure**

Lastly, determine the response if the validation fails.

```
if ($validator->fails()) {
    return redirect('form')->withErrors($validator)->withInput();
}
```
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
```
This command generates a new class in the _App_\_Http_\_Requests_ directory, a PHP file where you can define all your custom validation rules.

2. **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',
        ];
    }
}
```
This method requires the email field to be valid, ensuring data adheres to rules for consistent and maintainable validation checks.

3. **Apply the Request Class in Your Controller**

Lastly, incorporate the EmailValidationRequest in your controller method.

```
public function store(EmailValidationRequest $request)
```
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,}$
```
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
}
```
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](https://mailtrap.io/blog/email-verification-tools/), 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](https://www.zerobounce.net/services/email-validation/), 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.

2. C**onfigure API Key**

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

```
ZEROBOUNCE_API_KEY=your_api_key_here
```

3. **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();
}
```
This function sends a GET request to ZeroBounce, which checks the email address for validity and deliverability, returning a JSON response.

4. **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.']);
    }
}
```
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.

2. **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
    }
}
```
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.');
                }
            }],
        ];
    }
}
```

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

```
use App\Http\Requests\StoreUserRequest;

public function store(StoreUserRequest $request)
{
    // Process valid email
}
```

## 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](https://mailtrap.io/email-sandbox/)—a part of the more extensive [Mailtrap Email Delivery Platform](https://mailtrap.io/).

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k706epq7fe8z7itd3i48.png)

**[Test Emails with Mailtrap for Free
](https://mailtrap.io/register/signup)**

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kf9fep8o1gizzk1v4v40.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hsemz4aycir66k2l417e.png)

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](https://youtu.be/AveaJc6c3fI)**

## 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! 😉

- [Send Email in Laravel with Gmail SMTP: Code Snippets [2024]](https://mailtrap.io/blog/laravel-send-email-gmail/) 
- [Laravel Email Testing: Mailtrap vs. Other Options](https://mailtrap.io/blog/laravel-email-testing/)
- [Laravel Mail Queue Tutorial | Mailtrap](https://mailtrap.io/blog/laravel-mail-queue/)
- [Laravel Email Notification Tutorial | Mailtrap](https://mailtrap.io/blog/laravel-notification-tutorial/)

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](https://mailtrap.io/blog/laravel-email-validation/)!