Register now and start sharing your code snippets.
-->

Validating an email address in Java

Java posted about 1 year ago by marko

The source of the regexp is this site: Email unlimited. According to Wikipedia the regexp on the source page validates the email address according to RFC 2822 – Internet Message Format. I have still to write a comprehensive test suite, but the tests I do have for this validator pass.

   1  public class EmailValidator {
   2    public static boolean validate(final String emailAddress) {
   3      if ( emailAddress == null ) return false;
   4      String patternStr = "^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$";
   5      Pattern emailPattern = Pattern.compile(patternStr);
   6      return emailPattern.matcher(emailAddress).matches();
   7    }
   8  }

Tagged email, validator, regexp, java, rfc 2822