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

  • niceandsimple@example.com
  • very.common@example.com
  • a.little.lengthy.but.fine@dept.example.com
  • disposable.style.email.with+symbol@example.com
  • user@[IPv6:2001:db8:1ff::a0b:dbd0]
  • "much.more unusual"@example.com
  • "very.unusual.@.unusual.com"@example.com
  • "very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com
  • 0@a
  • postbox@com (top-level domains are valid hostnames)
  • !#$%&'*+-/=?^_`{}|~@example.org
  • "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~  ? ^_`{}|~.a"@example.org
  • ""@example.org

Invalid email addresses

  • Abc.example.com (an @ character must separate the local and domain parts)
  • Abc.@example.com (character dot(.) is last in local part)
  • Abc..123@example.com (character dot(.) is double)
  • A@b@c@example.com (only one @ is allowed outside quotation marks)
  • a"b(c)d,e:f;gi[j\k]l@example.com (none of the special characters in this local part is allowed outside quotation marks)
  • just"not"right@example.com (quoted strings must be dot separated, or the only element making up the local-part)
  • this is"not\allowed@example.com (spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a slash)
  • this\ still\"not\\allowed@example.com (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 :
 ^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$
 
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 = "anuj@google.com";
        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 : http://goldenpackagebyanuj.blogspot.in/