With the release of Laravel 5.8 e-mail validation changed to comply with the RFC standards. That means when using the email
rule the following e-mail address will now pass: user@tld. This may be great for local intranets that utilize e-mail addresses like this, but who is really doing that? Most are trying to validate e-mails in the following format: user@sld.tld. Before Laravel 5.8 this technically valid e-mail address would fail, but that was also how the majority of Laravel developers wanted it to work.
This e-mail validation rule works in conjunction with Laravel's built in email
rule to also require domains to have at least a second level domain. To use this rule you would write something like: 'email' => ['required', 'email', new EmailHasSecondLevelDomain()]
. Now e-mails will validate the way you expect for a public Internet website.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class EmailHasSecondLevelDomain implements Rule
{
/**
* Technically a valid e-mail is:
*
* user@com
* user@localhost
*
* However, we want to deny these sort of e-mails and require a secondary domain
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return preg_match("/\.[a-z]{2,63}$/i", $value);
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'E-mail address must have a second level domain such as user@sld.tld';
}
}
This code snippet was published on It was last edited on