How to block specific email domains from registering in Laravel

Spread the love

Hello Guys,

Learn how to block specific email domains from registering on your Laravel website with this step-by-step guide. Discover effective techniques to enhance user registration security and keep unwanted domains at bay.

Example of block specific email domains from registering:

Create a custom rule

To establish a custom BlockEmailDomain rule, execute the subsequent command in your console:

php artisan make:rule BlockEmailDomain

A new rule class called “BlockEmailDomain” will be automatically generated within your application. To implement this, simply insert the provided code into the designated file by navigating to the specified location.

<?php

namespace App\Rules;

use App\Models\DomainBlockList;
use Illuminate\Contracts\Validation\Rule;

class BlockEmailDomain implements Rule
{
    protected $blockList;

    public function __construct($blockList)
    {
        $this->blockList = $blockList;
    }

    public function passes($attribute, $value)
    {
        $domain = substr(strrchr($value, "@"), 1);

        if (count(explode('.',$domain))>2) {
            $domain=explode('.',$domain,2)[1];
        }

        if($this->blockList->where('domain', $domain)->count())
        {
            return false;
        }else{
            return true;
        }
    }

    public function message()
    {
        return 'The email domain is not allowed.';
    }
}

The custom BlockEmailDomain rule is subsequently integrated into the validation array of the email field

Also Read: How to Crop an Image Before Uploading in LARAVEL 10

use App\Models\DomainBlockList;
use App\Rules\BlockEmailDomain;
...
...
...

$blockList = DomainBlockList::where('active',1)->get();

        return Validator::make($data, [
            'name'     => ['required', 'string', 'max:255'],
            'email' => [
                'required', 'string', 'email', 'max:255', 'unique:users',
                new BlockEmailDomain($blockList)
            ],
            'password' => ['required', 'string', 'min:8', 'confirmed']
        ]);

When trying to sign up using an email address that isn’t on our approved list, an error message will be displayed.

Explore our Laravel blog section for insightful content and helpful tips.

Leave a Comment