Validate an email address in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import org.apache.commons.validator.routines.EmailValidator; class Main { // Validate an email address using the validator public static boolean emailValidator(String email) { // Get an instance of the EmailValidator class EmailValidator validator = EmailValidator.getInstance(); // Return true if the email address is valid return validator.isValid(email); } public static void main(String[] args) { // Validate an email address if (emailValidator(email)) { System.out.println("The email address " + email + " is valid"); } else { System.out.println("The email address " + email + " is invalid"); } } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.regex.Matcher; import java.util.regex.Pattern; class Main { // Define the regular expression for email validation private static final String EMAIL_REGEX = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"; // Compile the regular expression into a pattern private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX); // Validate an email address using the pattern public static boolean emailValidator(String email) { if (email == null) { return false; } // Create a matcher for the email address Matcher matcher = EMAIL_PATTERN.matcher(email); // Return true if the email address matches the pattern return matcher.matches(); } public static void main(String[] args) { // Validate an email address if (emailValidator(email)) { System.out.println("The email address " + email + " is valid"); } else { System.out.println("The email address " + email + " is invalid"); } } } |
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:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)