To restrict email input to Gmail addresses only, you can modify your existing code slightly. Instead of using the complex regex validation, simply check if the domain part of the email is ‘gmail.com’. Here’s a more straightforward approach:
function is_gmail($email) {
$parts = explode('@', $email);
return (count($parts) == 2 && strtolower($parts[1]) === 'gmail.com');
}
if (!is_gmail($user_email)) {
$error_msg = 'Please enter a valid Gmail address. Only Gmail accounts are accepted.';
echo $error_msg . '<br><a href="#" onclick="history.back()">Go back</a>';
}
This method is simpler and directly checks for the Gmail domain. It’s worth noting that this approach doesn’t validate the local part of the email address, so you might want to add additional checks if needed.
I’ve been in your shoes before, and I can tell you that restricting emails to Gmail can be tricky. Here’s what worked for me:
function is_valid_gmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match('/@gmail\.com$/i', $email);
}
if (!is_valid_gmail($user_email)) {
$error_msg = 'Sorry, we only accept Gmail addresses at this time.';
echo $error_msg . '<br><a href="javascript:history.back()">Go back</a>';
exit;
}
This approach first uses PHP’s built-in email validation, then checks specifically for the Gmail domain. It’s robust and handles edge cases well. Just remember, some users might have custom Gmail domains for Google Workspace, so consider if you need to account for those too.