Validate email addresses

When a user inputs an email address, it may be validated by passing it to the constructor of InternetAddress. If it doesn't comply with RFC822, then a checked exception will be thrown.

Note that a simple local address, such as "joe", complies with RFC822. If this type of address is undesired (and it usually is), then some extra validation will be needed.

Example

Here's a class that validates email addresses through the static method isValidEmailAddress. Note that it treats local addresses as invalid (as implemented by the call to hasNameAndDomain).


package hirondelle.web4j.util;

import java.util.regex.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Static convenience methods for common web-related tasks.
*/
public final class WebUtil {
  
  /**
  * Validate the form of an email address.
  *
  * <P>Return <tt>true</tt> only if 
  *<ul> 
  * <li> <tt>aEmailAddress</tt> can successfully construct an 
  * {@link javax.mail.internet.InternetAddress} 
  * <li> when parsed with "@" as delimiter, <tt>aEmailAddress</tt> contains 
  * two tokens which satisfy {@link hirondelle.web4j.util.Util#textHasContent}.
  *</ul>
  *
  *<P> The second condition arises since local email addresses, simply of the form
  * "<tt>albert</tt>", for example, are valid for 
  * {@link javax.mail.internet.InternetAddress}, but almost always undesired.
  */
  public static boolean isValidEmailAddress(String aEmailAddress){
    if (aEmailAddress == null) return false;
    boolean result = true;
    try {
      InternetAddress emailAddr = new InternetAddress(aEmailAddress);
      if (! hasNameAndDomain(aEmailAddress)) {
        result = false;
      }
    }
    catch (AddressException ex){
      result = false;
    }
    return result;
  }

  private static boolean hasNameAndDomain(String aEmailAddress){
    String[] tokens = aEmailAddress.split("@");
    return 
      tokens.length == 2 &&
      Util.textHasContent(tokens[0]) && 
      Util.textHasContent(tokens[1]) 
    ;
  }
  
  //..elided
}
 



See Also :
Send trouble-ticket emails
A Web App Framework - WEB4J
Launch other applications
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -