Monday, September 22, 2008

How to validate e-mail?

A simple regex that can be used to validate e-mail address - ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$. This can be readily used with client side JavaScript. Following is an example:

function validateEmail(email) {
return (email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/ig) != null) ? true : false;
}

javax.mail.internet.InternetAddress can also be used to validate e-mail address. Following is an example:

try {
InteretAddress address = new InternetAddress(emailstring);
address.validate();
return true;
}
catch(AddressException e) {
return false;
}

No comments: