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

javax.mail.internet.InternetAddress can also be used to validate e-mail address. Following is an example:
  1. try {  
  2.  InteretAddress address = new InternetAddress(emailstring);  
  3.  address.validate();  
  4.  return true;  
  5. }  
  6. catch(AddressException e) {  
  7.  return false;  
  8. }  

No comments: