Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

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.

That’s good.

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

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



This post first appeared on Neutron Dev, please read the originial post: here

Share the post

Laravel — Improve Email Validation

×

Subscribe to Neutron Dev

Get updates delivered right to your inbox!

Thank you for your subscription

×