« Back to Blog

How to Create a Custom API-based Validation Rule with Laravel

Published on: by Jason Gilmore

The Laravel framework offers a rich array of input validation rules. Using these rules you can easily validate e-mail addresses, dates, integer sizes, MIME types, and much more. You can view a complete list of validators in the Laravel documentation. It's also possible to create a custom validator containing any kind of logic you see fit to determine whether a certain type of user input is acceptable, and can even incorporate third-party APIs to assist with this goal. In this tutorial, we will create a custom validation rule that validates an email address against the EmailReputationAPI, a service used to help companies more effectively manage leads by identifying invalid, personal, and high-risk email addresses.

Installing and Configuring the EmailReputationAPI Composer Package

First, we need to install the EmailReputationAPI Composer package for Laravel. We can do this using Composer:

$ composer require emailreputationapi/reputation

Next, publish the package's configuration file:

$ php artisan vendor:publish --tag="reputation-config"

This is the contents of the published config file (`config/reputation.php`):

return [
    'api_key' => env('EMAIL_REPUTATION_API_SECRET'),
    'api_url' => env('EMAIL_REPUTATION_API_URL'),
];

You can find your API key in your EmailReputationAPI dashboard. If you don't have an account, you can sign up for free. Add the following two variables to your .env file:

EMAIL_REPUTATION_API_SECRET='your-api-key'
EMAIL_REPUTATION_API_URL='https://emailreputationapi.com/api/v1'

Creating the Custom Laravel Validation Rule

Next let's create the custom Laravel validation rule that will validate an email address against the EmailReputationAPI. We can do this using the make:rule Artisan command:

$ php artisan make:rule Reputation

This will create a new app/Rules/Reputation.php file. Open this file and replace the boilerplate code with the following:

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

use EmailReputationAPI\Reputation\Email as EmailReputationAPI;

class Reputation implements ValidationRule
{

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $reputation = new EmailReputationAPI();
        $validate = $reputation->validate($value);
        if ($validate->syntax == "invalid") {
            $fail('This email address is invalid.');
        } elseif($validate->tld == "false") {
            $fail('Invalid TLD. Please provide a valid email address.');
        } elseif($validate->disposable == "true") {
            $fail('Anonymized/disposal email addresses are not allowed.');
        }
    }
}

Keep in mind the properties exposed by the EmailReputationAPI API are not exhaustively used in this example, and may change over time. You can view the latest documentation for the API here.

Updating the User Registration Logic

Laravel will by default house the user registration validation logic directly within the Register controller. Open app/Http/Controllers/Auth/RegisterController.php and add the following line to the top of the file:

use App\Rules\Reputation;

Finally, go to the validator method and update the $validator array's email key to include the Reputation rule:

$validator = Validator::make($data, [
            'name'     => ['required', 'string', 'max:255'],
            'company'  => ['required', 'string', 'max:255'],
            'email'    => ['required', 'string', 'email', 'max:255', 'unique:users', new Reputation],
            'password' => ['required', 'string', 'min:8'],
]);

With this change in place, the user registration form will now validate the email address against the EmailReputationAPI before allowing the user to register. Let's test it out by attempting to register for an EmailReputationAPI account using a disposable email address:

Preventing a disposal address from being used during registration

As you can see in the above screenshot, the user has been prevented from using a disposable email address to register on the site. This is just one example of how you can use the EmailReputationAPI to help prevent invalid, personal, and high-risk email addresses from being used on your site.

Conclusion

Hopefully this tutorial has given you a better idea of how to create a custom API-based validation rule with Laravel. If you have any questions or feedback, please email us. We'd love to hear from you!