Custom Email Validation Laravel 8

Christina Kaloodee
2 min readJan 27, 2021

With one way or another, the need for better email validation will find the way to find you. You probably already checked out the documentation and see a lot of options that may be a good fit for you.

If not, there is another solution too, where you can create your own validation rules and use them properly. Why to do something like this?
The need in my case, was to avoid the extra “Fetching DNS Resource Records” call that the dns function curries but also prevent as much as possible spam or invalid emails. The dns check by the way is a great choice if you want to keep a clean email marketing list. But that is a different topic. Quite a challenge if you are new to this thought..

The first question that came into my mind was: “What are the criteria that make an email address valid?”. After a little search I stopped in this post “How to Find or Validate an Email Address” that explains really well the logic behind email validation using a regex. That was it, the regex idea was actually a good choice here.

So after that, as I was trying to understand that regex, the test driven approach (TDD) helped a lot here. I used data providers to list all the not accepted emails and actually visualize that regex. It’s also a great way to determine what you don’t want to be stored in your database.

When I finally came up with a regex, I added it in the custom validation rule check like so:

Then, in order to be able to use it, add it in the AppService Provider.

That’s it. You are ready to use it in you Validation Form Requests or wherever else you want, just like any other Laravel rule.

But wait a minute.. We are not done yet. What about this test case? We cannot allow this.. We need to sanitize email addresses before validation. Think about that: What if you could register to a site with your@example.email as an account, but also Your@example.email like a different account.

In my case again, I needed a general approach to apply sanitization in more that one case, so I created a Sanitizer middleware for this. To be able to give a simple example here, I simplified the logic a little bit.

You may see the github repo too for more details. I would love to hear your thoughts too.

--

--

Christina Kaloodee

I love great designs and the back-end side is my passion. Always curious about what's hiding under the hood. Coffee and tea lover too.