Warning!!! This post is for the Uber-Apex Programmer and should not be attempted by novices. It may cause headaches, hair-loss, eye-strain and more, but it’s well worth it!
On two different occasions in the last week a client has needed email addresses in salesforce.com validated. The only true form of validation for an email address is to send an email and see if it bounces. This post doesn’t cover that. Instead, we’re focusing on the formatting of the email address.
According to a salesforce.com solution (login required), as of the Winter ’08 release, salesforce.com validates email addresses as follows:
1. For the local part of the email address we accept the following characters. (The local part is anything before the @ sign.)
abcdefg.hijklmnopqrstuvwxyz!#$%&’*/=?^_+-`{|}~0123456789
Note: The character dot “.” is supported; provided that it is not the first or last character in the local-part
2. For the domain part of the email address we accept. The domain part is anything after the @ in an email address:
0-9 and A-Z and a-z and dash “-“
3. Example email address:
abcdefg.hijklmnopqrstuvwxyz!#$%&’*/=?^_+-`{|}~0123456789@acme-inc.com
Our goal was to perform the same validation via Apex prior to saving the record. This can be done using a lot of String methods and If statements, but really this type of comparison is best done with a Regular Expession.
Apex already has built-in Pattern and Matcher Classes for this purpose, so all we had to do was come up with the right regular expression. Thanks to some tips at www.regular-expressions.info it was actually an easy task to complete. It was so easy, that we’re releasing this code into the wild for all of our customers (and competitors) to use.
String pat = '[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\*\\/\\=\\?\\^\\_\\+\\-\\`\\{\\|\\}\\~\'._%+-]+@[a-zA-Z0-9\\-.-]+\\.[a-zA-Z]+';
Boolean test = Pattern.matches(pat, email);