Email Validation using Laravel DNS Validation

Most of the Laravel developers use 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 string against RFC spec which means it validates whether string is valid email address or not.

Is RFC validation enough?

RFC’s perception of email is quite loose in terms of what it means by email. According to RFC, harry@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.

DNS Validation

To properly validate email and filter entered emails like harry@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 DNS validator, click here.

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

$faker->freeEmail function generates email from safe domains like gmail, yahoo and hotmail. So, feel free to replace $faker->email with $faker->freeEmail.

2 thoughts on “Email Validation using Laravel DNS Validation”

Leave a Comment