Email validation is a common task that many developers need to perform when working with web applications, forms, or databases. Email validation can help prevent spam, ensure data quality, and avoid errors or exceptions. In this post, we will learn how to validate an email address in Java using different methods and libraries.

An email address consists of two parts: a local part and a domain part, separated by an @ symbol. The local part can contain alphanumeric characters, dots, underscores, hyphens, and plus signs. The domain part can contain alphanumeric characters, dots, and hyphens. The domain part must also have at least one dot and a valid top-level domain (TLD) such as .com, .org, .net, etc. Please refer to Wikipedia for correct syntax, and sample valid and invalid email addresses.

 
Whenever we’re asked to validate an email address in Java, the first thing that came to our mind is writing our own regular expression. The idea is great; the only problem is no matter how hard we try, one can’t come up with a perfect solution that covers all cases. So, it is recommended to use a library or already verified regular expression to validate an email address, which is pretty good but still doesn’t guarantee to catch all possible errors in an email address.

1. Using Apache Commons Validator

The Apache Commons Validator library provides various validation utilities for Java. One of them is the EmailValidator class, which can validate an email address according to RFC 822 standards. We can use this class to validate an email address in Java as follows:

Download Code

Output:

The email address [email protected] is valid

 
It can also handle more complex cases such as internationalized domain names, quoted strings, comments, etc. We can also customize the validator by setting some parameters such as allowing local addresses, domain names without TLDs, etc.

2. Using RFC-5322 Compliance Regex

We can use a regular expression to validate an email address by checking if it matches the pattern of a valid email address. For example, we can use RFC 2822 compliant regex, which defines the syntax that valid email addresses must adhere to. To use this regular expression in Java, we can use the Pattern and Matcher classes from the java.util.regex package. For example:

Download  Run Code

Output:

The email address [email protected] is valid

 
This method can validate most of the common email addresses, but it may also reject some valid ones or accept some invalid ones. Therefore, we should use this method with caution and test it thoroughly with different cases. We can also modify the regular expression to suit our needs, but keep in mind that it is impossible to create a perfect regular expression that covers all the possible variations of valid email addresses.

That’s all about validating an email address in Java.

 
Also See:

Validate an IP address in Java