A Java email address validation class

In this post I thought I’d share the source code for my Java email address validator class.

I’m not sure if there’s a big need for it ... I wrote it a long time ago, and I think I created it because Java’s javax.mail.internet.InternetAddress class wasn’t properly validating email addresses at that time. For instance, I think it would allow the string “fred” to be a valid email address, but on the internet you really want to see something like “fred@foo.bar“. So I think that’s where this class comes from.

In this post I’m including the source code for my EmailAddressValidator class, as well as a class that implements a bunch of Junit tests against the public method of the EmailAddressValidator class.

The source code for both classes is free, do with them what you will. I'll be glad to hear of any mistakes I've made, or improvements you make.

Java email address validator class

Here’s the EmailAddressValidator class:

package com.devdaily.web.email;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;
import java.util.StringTokenizer;

/**
 * A class to provide stronger validation of email addresses.
 * devdaily.com, no rights reserved. :)
 *
 */
public class EmailAddressValidator
{
  public static boolean isValidEmailAddress(String emailAddress)
  {
    // a null string is invalid
    if ( emailAddress == null )
      return false;

    // a string without a "@" is an invalid email address
    if ( emailAddress.indexOf("@") < 0 )
      return false;

    // a string without a "."  is an invalid email address
    if ( emailAddress.indexOf(".") < 0 )
      return false;

    if ( lastEmailFieldTwoCharsOrMore(emailAddress) == false )
      return false;

    try
    {
      InternetAddress internetAddress = new InternetAddress(emailAddress);
      return true;
    }
    catch (AddressException ae)
    {
	  // log exception
      return false;
    }
  }


  /**
   * Returns true if the last email field (i.e., the country code, or something
   * like .com, .biz, .cc, etc.) is two chars or more in length, which it really
   * must be to be legal.
   */
  private static boolean lastEmailFieldTwoCharsOrMore(String emailAddress)
  {
    if (emailAddress == null) return false;
    StringTokenizer st = new StringTokenizer(emailAddress,".");
    String lastToken = null;
    while ( st.hasMoreTokens() )
    {
      lastToken = st.nextToken();
    }

    if ( lastToken.length() >= 2 )
    {
      return true;
    }
    else
    {
      return false;
    }
  }

}

Junit tests for the email address validator

And here's the Junit class I created to test the EmailAddressValidator class:

package com.devdaily.web.email;

import junit.framework.*;
import com.devdaily.web.email.EmailAddressValidator;

/**
 * A class to test the EmailAddressValidator class.
 * devdaily.com. no rights reserved. :)
 */
public class EmailAddressValidatorTests extends TestCase
{

  /**
   * Set up work to be done before test cases.
   */
  protected void setUp()
  {
  }

  /**
   * do a tear down after each test
   */
  protected void tearDown()
  {
  }


  //---------------------------------------------------------------------------------------------//

  public void testAl()
  {
    String address = "al@foobar.com";
    boolean expectedResult = true;
    boolean actualResult = EmailAddressValidator.isValidEmailAddress(address);
    assert( "\ntestAl, EXPECTED: " + expectedResult + ", GOT: " + actualResult,
            (expectedResult==actualResult) );
  }

  //---------------------------------------------------------------------------------------------//

  public void testBlank()
  {
    String address = "";
    boolean expectedResult = false;
    boolean actualResult = EmailAddressValidator.isValidEmailAddress(address);
    assert( "\ntestBlank, EXPECTED: " + expectedResult + ", GOT: " + actualResult,
            (expectedResult==actualResult) );
  }

  //---------------------------------------------------------------------------------------------//

  public void testNull()
  {
    String address = null;
    boolean expectedResult = false;
    boolean actualResult = EmailAddressValidator.isValidEmailAddress(address);
    assert( "\ntestBlank, EXPECTED: " + expectedResult + ", GOT: " + actualResult,
            (expectedResult==actualResult) );
  }

  //---------------------------------------------------------------------------------------------//

  public void testYo()
  {
    String address = "yo@foobar.com";
    boolean expectedResult = true;
    boolean actualResult = EmailAddressValidator.isValidEmailAddress(address);
    assert( "\ntestYo, EXPECTED: " + expectedResult + ", GOT: " + actualResult,
            (expectedResult==actualResult) );
  }

  //---------------------------------------------------------------------------------------------//

  public void testAtSymbols()
  {
    assert( "\ntestAtSymbols1", !EmailAddressValidator.isValidEmailAddress("@") );
    assert( "\ntestAtSymbols2", !EmailAddressValidator.isValidEmailAddress("@devdailly") );
    assert( "\ntestAtSymbols3", !EmailAddressValidator.isValidEmailAddress("@devdailly.com") );
    assert( "\ntestAtSymbols4", !EmailAddressValidator.isValidEmailAddress(" @devdailly.com") );
    assert( "\ntestAtSymbols5", !EmailAddressValidator.isValidEmailAddress("foo @devdailly.com") );
    assert( "\ntestAtSymbols6", !EmailAddressValidator.isValidEmailAddress("@devdailly .com") );
    assert( "\ntestAtSymbols7", !EmailAddressValidator.isValidEmailAddress("@devdailly. com") );
    assert( "\ntestAtSymbols8", !EmailAddressValidator.isValidEmailAddress("foo@devdailly") );
    assert( "\ntestAtSymbols9", !EmailAddressValidator.isValidEmailAddress("foo@ devdailly") );
  }

  //---------------------------------------------------------------------------------------------//

  public void testSingleName()
  {
    assert( "\ntestSingleName1", !EmailAddressValidator.isValidEmailAddress("al") );
    assert( "\ntestSingleName2", !EmailAddressValidator.isValidEmailAddress("barney") );
  }

  //---------------------------------------------------------------------------------------------//

  public void testlongBlank()
  {
    assert( "\ntestlongBlank1", !EmailAddressValidator.isValidEmailAddress(" ") );
    assert( "\ntestlongBlank2", !EmailAddressValidator.isValidEmailAddress("          ") );
    assert( "\ntestlongBlank3", !EmailAddressValidator.isValidEmailAddress("                                                     ") );
  }

  //---------------------------------------------------------------------------------------------//

  public void testCrazyStuff()
  {
    assert( "\ntestCrazyStuff1", !EmailAddressValidator.isValidEmailAddress(".@") );
    assert( "\ntestCrazyStuff2", !EmailAddressValidator.isValidEmailAddress("@.") );
    assert( "\ntestCrazyStuff3", !EmailAddressValidator.isValidEmailAddress("@.@.@.@.") );
    assert( "\ntestCrazyStuff4", !EmailAddressValidator.isValidEmailAddress("a@b.c") );
    assert( "\ntestCrazyStuff5", !EmailAddressValidator.isValidEmailAddress("foobar@yahoo.c") );
    assert( "\ntestCrazyStuff6", !EmailAddressValidator.isValidEmailAddress("@@@.cc") );
    assert( "\ntestCrazyStuff7", !EmailAddressValidator.isValidEmailAddress("ala@foo@bar.com") );
  }

  //---------------------------------------------------------------------------------------------//

  public void testIpAddresses()
  {
    //assert( "\ntestIpAddresses", EmailAddressValidator.isValidEmailAddress("foo@127.0.0.1") );
  }

  //---------------------------------------------------------------------------------------------//


  public static void main(String args[])
  {
    junit.textui.TestRunner.run(EmailAddressValidatorTests.class);
  }

  public EmailAddressValidatorTests(String name)
  {
    super(name);
  }

  public static Test suite()
  {
    TestSuite suite = new TestSuite();

    // run tests manually
    //suite.addTest( new EmailAddressValidatorTests("testNumericAddress1") );
    //return suite;

    // or, run tests dynamically
    return new TestSuite(EmailAddressValidatorTests.class);
  }

}

Sorry, I don’t have the time to deeply describe this code, but I hope the unit tests give you a good idea of how to use the email address validator. In summary, if you were looking for some Java code to help you validate email addresses, I hope this is helpful.