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:
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.