Explain Codes LogoExplain Codes Logo

What is the best Java email address validation method?

java
email-validation
best-practices
regular-expressions
Alex KataevbyAlex Kataev·Oct 22, 2024
TLDR

Here's a quick and direct way to get email validation done using the JavaMail API's InternetAddress class:

public static boolean isValidEmail(String email) { // Trying not to trip over any irregular email formats here try { new InternetAddress(email).validate(); return true; } catch (Exception ex) { // Oops! seems like we did trip return false; } }

Plug the email into isValidEmail method, and it'll do the hard yards, verifying format in compliance with RFC 822 standards. But remember there's more to email validation than just RFC 822!

Achieving robust validation

Superficial validation is good, but if you want a sturdy, ironclad validation, let's have a look at some additional practices you can weave in.

Tap into Apache Commons’ Validator

The Apache Commons Validator offers a robust EmailValidator that's understanding of the ever-evolving internet domain sprawl:

boolean isValid = EmailValidator.getInstance().isValid(email); // Faster than Homelander at catching bogus emails!

Email confirmation – the fail-safe

Make your users prove their creds by sending them an activation link. All that is needed is a simple:

public static void sendConfirmationEmail(String email) { // This function still believes in the good old "Check your inbox (or spam!)" school of thought }

This not only confirms that it wasn't a typo, it also verifies that the email address exists and user has access to it.

Consider regular expressions (Regex)

Got a taste for regex? Make sure your patterns are well-oiled and flexible enough to accommodate any unprecedented changes:

Pattern emailPattern = Pattern.compile("^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"); // I have a love-hate relationship with Regex. It's mostly hate, though!

Catering to edge-cases

Some workplaces might require local addresses as valid emails too. Here's an example of how to handle that with Apache Commons:

boolean isValid = EmailValidator.getInstance(true).isValid(email); // This one has that 'door's always open' policy!

Validate that domain

For environments where you don't need surprises (yes, looking at you, enterprise applications), go that extra mile and validate the domain as well:

public static boolean isDomainValid(String domain) { // Sniper-esque focus on the domain only }

Ensure the domain not only exists but is also actively registered. You might end up finding new friends at ICANN!

Upgrading validation for production

When deploying to production, a resilient and thorough validation is crucial.

Evaluate your options before committing

Don't settle right away. Review, compare and then commit to a solution that suits your needs the best.

Accept that perfection is an illusion

It's a given that you might miss out on some cases. Adopt a loose and practical validation technique that minimizes false rejections.

Simplicity is the ultimate sophistication

Leonardo da Vinci said that. The same applies when creating your validation logic. Simplicity breeds transparency, which in turn reduces the possibility of unforced errors.