Email Validation using Laravel 11 DNS Validation

Email Validation using Laravel 11 DNS Validation

Email Validation using Laravel 11 DNS Validation

Most of the Laravel developers use the default email validation service provided by Laravel. And it does its job to some extent. Our regular email validation looks like this:

'email' => 'required|email|unique:users|max:255'

This default validator checks the string against RFC spec which means it validates whether a string is a valid email address or not.

1 - Is RFC validation enough?

RFC’s perception of email is quite loose in terms of what it means by email. According to RFC, tttt@gmail and [email protected] are valid email.

Sending verification email is a solution to this problem but what if a system does not need to verify its user? To address this problem, we need another approach.

2 - DNS Validation

To properly validate emails and filter entered emails like tttt@gmail and [email protected], there is an inbuilt functionality in Laravel i.e. DNS validator. To apply that validator all you need to do is change email validation as follows:

'email' => 'email'

– to

'email' => 'email:rfc,dns'

This way you can apply both DNS and RFC validator to your email address. For a DNS validator, click here.

Faker is a really helpful tool for testing but is the default email set by Faker valid? No, they are not. $faker->email provides valid email but only sometimes. But there is no need to panic, faker provides us with $faker->freeEmail which provides safe emails.

$faker->freeEmail the function generates an email from safe domains like Gmail, Yahoo, and Hotmail. So, feel free to replace $faker->email it with $faker->freeEmail.

All Comments