EmailAddress Validation in Java
For something as well-established as email address format, the difference between two approaches is minuscule. Then again, fifty years ago, people never saw the need to use 4 digits for encoding years, so...
The only 'pitfall' with using the regex from Apache Commons, is that its functionality for validating an email address isn't "Java standard". To what extent that affects you as a developer? depends on how paranoid you are.
On the other hand, the standard Java implementation might be less efficient. You'd have to construct an InternetAddress
and validate it. Looking at JavaMail's source code, I could see this:
/**
* Check that the address is a valid "mailbox" per RFC822.
* (We also allow simple names.)
*
* XXX - much more to check
* XXX - doesn't handle domain-literals properly (but no one uses them)
*/
(The XXX
seems to be some sort of a note, or a "to do" item)
You can use an EmailValidator from Apache Commons Validator library for that:
import org.apache.commons.validator.EmailValidator;
...
EmailValidator validator = EmailValidator.getInstance();
if (validator.isValid(email)) {
// is valid, do something
} else {
// is invalid, do something
}
isValid method checks if a field has a valid e-mail address.
This is the best Java email address validation method according to this question What is the best Java email address validation method?
I've just tested it, and apparently the performance on InternetAddress is substantially better then using EmailValidator
package com.avaya.oss.server.errors;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.validator.EmailValidator;
public class TestValidationTypes {
static String email = "[email protected]";
static int maxItr = 10000;
public static void main(String[] args) throws AddressException {
long start = System.currentTimeMillis();
for (int i = 0; i < maxItr; i++) {
EmailValidator.getInstance().isValid(email);
}
System.out.println("EmailValidator duration: " + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < maxItr; i++) {
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
}
System.out.println("InternetAdress duration: " + (System.currentTimeMillis() - start));
}
}
Output:
EmailValidator duration: 1195
InternetAdress duration: 67
The results are that EmailValidator took ~20 times longer: