Validate email address in java

In this post, we will see how to validate email address in java.

There are times when you have to validate email address provided by user. You might want to write your own logic to validate email addresses but there are lots of standard regular expressions or libraries which can help you validate email address and provide great results.

Email address is made up of local part, @ and followed by domains. You can go through wiki page for format of email address.


Using regular expressions

We can use regular expression provided by OWASP Validation Regex Repository which is considered to be safe and will solve the purpose in most of the cases.

Here is the regular expression

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

Here is complete java program for email address validation in java

When you run above program, you will get below output

[email protected] is valid email
@java2blog.com is invalid email
[email protected] is valid email

Using apache common validator library

You can also use inbuilt apache librabry to validate the address. If you are using maven, then you need to add below dependency in your pom.xml.

Here is java program for the same.

When you run above program, you will get below output

[email protected] is valid email
@java2blog.com is invalid email
[email protected] is valid email

That’s all about validate email address in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *