Laravel — Improve Email Validation

Laravel improve email validation

Let’s assume that in your Laravel application, you have a form in which you use a Form Request to validate several fields, including the email.

To validate the email address, you use the email rule.

The issue with this method is that the email rule doesn’t verify if the email address is valid or if it can receive emails.

Take this simple feature test for example.

The email is invalid, yet the test passes.

Laravel Form Request email validation with invalid email passes feature test

That’s why in this tutorial, I will show you how to validate an email address against standard RFC-like email validation, and if there are DNS records that signal that the server accepts emails.

🎥 Prefer a video guide instead? Check this out:


Validate RFC & DNS

The solution is quite simple.

We need to add two extra parameters to the email rule.

These are rfc,dns.

Under the hood, Laravel uses the EmailValidator package to validate if an email address meets the RFC rules and if there are DNS records indicating that the server accepts emails.

Even if you don’t use Laravel, the good news is that you can implement the EmailValidator package in any PHP project because it’s not dependent on Laravel.

For more information, please check its documentation.

Coming back to the feature test, let’s run it again and it should fail with an error saying the email field must be a valid email address.

Laravel Form Request email validation invalid email fails test

That’s good.

Let’s change the email to a valid one and run the test again.

Laravel Form Request email validator with valid email address passes feature test

The test passes ✅

Generate valid email addresses with Faker

If you are using Faker to generate fake email addresses, make sure to use $faker->freeEmail() instead of $faker->email().

$faker->email() generates a random email address with a random domain, so there’s a chance that it will be invalid.

$faker->freeEmail() generates an email address using a list of allowed domains, so we can assume those emails are valid.

For more information on this, you can check out this link.

That’s all 🥳

Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.