Java email address validation



In Java email addresses could be validated either by Apache Commons validator or Java Mail APIs provided validation method.

Apache Commons is generally known as a solid project but is know to be restrictive. If you are already using Java Mail API for sending email then you really don't need this extra jar and Java Mail package should suffice your required mail.

But keep in mind though that you'll still have to send a verification email to the address if you want to ensure it's a real email, and that the owner wants it used on your site.
BTW using the official java email package is the easiest.


EmailAddressValidator.java
public static boolean isValidEmailAddress(String email) {
  
  if(email == null || "".equals(email))
   return false;
   
     boolean result = true;
     try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
        if ( ! hasNameAndDomain(email) ) {
         result = false;
    }
     } catch (AddressException ex) {
        result = false;
     }
     return result;
  }
private static boolean hasNameAndDomain(String aEmailAddress){
     String[] tokens = aEmailAddress.split("@");
     return 
      tokens.length == 2 &&
      StringUtils.hasText( tokens[0] ) && 
      StringUtils.hasText( tokens[1] ) ;
 }


No comments:

Post a Comment