Friday, July 27, 2012

Validate Email Address in Java

While building any web application we sometimes required to write email validation in our validation helper classes. You can validate email address using following way. All you need is to just have regular expression to validate Email Address and Java's Patten and Matcher classes.

Valid email addresses

  • user@[IPv6:2001:db8:1ff::a0b:dbd0]
  • "much.more unusual"
  • ""
  • "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"
  • 0@a
  • postbox@com (top-level domains are valid hostnames)
  • !#$%&'*+-/=?^_`{}|
  • "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~  ? ^_`{}|~.a"
  • ""

Invalid email addresses

  • (an @ character must separate the local and domain parts)
  • (character dot(.) is last in local part)
  • (character dot(.) is double)
  • (only one @ is allowed outside quotation marks)
  • a"b(c)d,e:f;gi[j\k] (none of the special characters in this local part is allowed outside quotation marks)
  • just"not" (quoted strings must be dot separated, or the only element making up the local-part)
  • this is"not\ (spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a slash)
  • this\ still\"not\\ (even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)

Regular expression to validate email address used in following program is :
Java Program to validate Email Address :

package com.anuj.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidation {

     * @param args
    public static void main(String[] args) {
        String email = "";
        boolean validemail = isEmailValid(email);

        if (validemail) {
            System.out.println("email is valid");
        } else {
            System.out.println("email is not valid");

    public static boolean isEmailValid(String email) {
        boolean emailValid = false;
        CharSequence emailstr = email;
        String exp = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        Pattern p = Pattern.compile(exp, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(emailstr);

        if (m.matches()) {
            emailValid = true;
        return emailValid;


Author : Anuj Patel
Blog :