Validate an Email Address in Java

This post covers various methods to validate an email address in Java.


 

An email address is made up of a local-part, an @ symbol, then a domain. Please refer Wikipedia for correct syntax and sample valid and invalid email address.

 
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 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 are pretty good but still don’t guarantee to catch all possible errors in an email address.

 

1. Using Apache Commons Validator

Apache Commons Validator package contains several standard validation routines. We can use EmailValidator class that provides validation methods to validate an email address according to RFC 822 standards.

 

Download   Run Code

Output:

The Email address [email protected] is valid

 

2. Using OWASP Validation Regex

We can also use OWASP Validation Regex which are considered to be very safe. Below regular expression can be used to check for a valid email Address.

^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$

 
ESAPI validation routine can also be used which uses the following regular expression.

Validator.Email=^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$

 

Download   Run Code

Output:

The Email address [email protected] is valid

 

 
Also See: Validate an IP address in Java

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz