How to restrict email domains to Gmail and Yahoo in Laravel registration?

I’m working on a Laravel project and need help with the registration form. I want users to only be able to sign up with Gmail or Yahoo email addresses. If they try to use any other email domain, I want to display an error message that says “Please enter a valid email address.”

Here’s what I’ve got in my registration controller so far:

protected function validateRegistration($data)
{
    return Validator::make($data, [
        'full_name' => 'required|string|max:255',
        'user_email' => 'required|string|email|max:255|unique:users',
        'user_password' => 'required|string|min:8|confirmed',
        'user_handle' => 'required|string|alpha_dash|max:30|unique:users',
    ]);
}

How can I adjust this to only accept Gmail and Yahoo email addresses? Any help would be greatly appreciated. Thanks!

To restrict email domains to Gmail and Yahoo, you can modify your validation rule for ‘user_email’ in the validateRegistration method. Here’s an updated version:

'user_email' => [
    'required',
    'string',
    'email',
    'max:255',
    'unique:users',
    function ($attribute, $value, $fail) {
        $domain = explode('@', $value)[1] ?? '';
        if (!in_array($domain, ['gmail.com', 'yahoo.com'])) {
            $fail('Please enter a valid email address (Gmail or Yahoo only).');
        }
    },
],

This approach uses a custom validation rule to check the email domain. It is more flexible than regex and easier to maintain if you need to add more domains in the future.

hey man, u can use regex for this. just add a rule to ur validator like this:

‘user_email’ => [‘required’, ‘string’, ‘email’, ‘max:255’, ‘unique:users’, ‘regex:/[1]+@(gmail|yahoo).com$/i’]

this’ll only allow gmail n yahoo addresses. hope it helps!


  1. a-zA-Z0-9._%± ↩︎