A Spring Validator to Block Email Domains

Web Development is not just building Web Sites, it’s managing them as well. NixMash Spring is primarily a Demo Site, but it supports Social Logins as well as user account registration. That requires vigilance with user accounts and user activity.

Lately we’ve been seeing a lot of suspicious new user email domains like these.

Not that they’re doing any harm, but most developers are pretty anal about who puts what in their database tables and application logs. That’s a good thing. So to take back some control of our Users table we created a Spring Validator to block user registration with emails that end with certain domains and Top Level Domains. Emails can be bogus, we don’t care, but as a matter of principle they can’t be from identified Spam origins like eamale.com.

So, back to our Spring Validator. We already had a CreateUserFormValidator on the User Registration form so we add a new validation method with the end result looking something like this.

The Service Behind the Scenes

Before looking at the Spring Service Component with the logic to block selected domains, here’s the AccessDTO object which will house the email properties. IsValid refers to the email structure while IsApproved is the final judge. A new AccessDTO object is constructed with the email address and is neither valid nor approved.

The Service strips the domain from the email address and compares it with two comma-delimited strings from an external .properties file: “EndsWith” and “DomainOverrides”. The reason for two lists, we can block emails ending with “mail.com” but will still pass through “gmail.com”, “hotmail.com”, etc.

Now we can add that method to our validator and we’re done!

Some Tests

Here is an excerpt of Email Domain filter logic tests. 1) “good.com” passes, 2) “printemailtext.com” has valid structure but is blacklisted. 3) Emails with the “.ru” TLD are not accepted.

With the result we saw at the top:

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.