Tuesday, February 28, 2012

How to Validate Email Address using Java Pattern


Validate an email address is easy if you have good valid pattern expression.   

package com.jsupport;

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

 * @author JSupport
public class ValidateEmailAddress {

    public boolean isValidEmailAddress(String emailAddress) {
        String expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = emailAddress;
        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        return matcher.matches();

    public static void main(String[] args) {
        ValidateEmailAddress vea = new ValidateEmailAddress();

        System.out.println(vea.isValidEmailAddress("info@jsupport.info"));      // Valide emaill address
        System.out.println(vea.isValidEmailAddress("info@jsup@port.info"));     // Invalide emaill address
        System.out.println(vea.isValidEmailAddress("info@jsupport.in_fo"));     // Invalide emaill address
        System.out.println(vea.isValidEmailAddress("in@fo@jsupport.info"));     // Invalide emaill address
        System.out.println(vea.isValidEmailAddress("info@jsupport.com.lk"));    // Valide emaill address

Here you will find how to validate email address using Java Mail API


Steven said...

Needs to support hyphens, apostrophes, and underscores.
Also, add a-z into [A-Z] to be able to remove the case_insensitive compile arg.

Paul Clapham said...

And good test cases would help too -- the ones in this post are hopelessly trivial. However you can't have good test cases unless you understand the requirements, which the poster clearly doesn't. I'm sure people who knew what they were doing could come up with a much longer list of faults. (For example there are top-level domains whose length exceeds 4 characters.)

JSupport said...

hypes,apostrophes??? its support underscores..

JSupport said...

I did not find any top level domains whose length exceeds 4 characters, that's why I make it to 4

Andrea said...

The regular expression doesn't match valid email address like "name+suffix@host.com".
There are more valid valid characters not accepted by your regurlar expression. As an example these are all valid: !#$%&'*+-/=?^_`{|}~.

As a reference look at Wikipedia: http://en.wikipedia.org/wiki/Email_address#Syntax
There you can find links to the official RFCs.

Giuseppe Moscarella said...

You could simply use JavaMail API:


JSupport said...

Yes we can use java Mail API here you will find How To Validate Email Address in Java Mail API

Java-Only said...

Regular Expressions in form validation

Post a Comment