Email Validation in APEX

If you enter an email address into an ’email’ type field in Force.com, it will validate that the value entered is a valid email, and won’t let you save the record with a bad email. But when you are integrating Salesforce with another system, that system may not perform the same level of verification. You often need to import the record into Salesforce regardless of whether the email is valid, but need to be able to handle bad emails so you don’t try and save a record with a bad email address.

So I always create a static method in a Utility class that I can use to check an email and return a boolean to tell me if the email is valid or not. If not, I can then save the email address to a non-email text field, and flag the record for review by a business user. The method uses a pattern match with a REGEX for matching against emails. I have always used the example from this post. But if you search for Email and Regex, you’ll find lots of examples. The one below seems to handle most scenarios though.


public static Boolean checkEmail (String semail) {
String InputString = semail;
String emailRegex = '([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})';
Pattern MyPattern = Pattern.compile(emailRegex);

// Then instantiate a new Matcher object "MyMatcher"
Matcher MyMatcher = MyPattern.matcher(InputString);

if (!MyMatcher.matches()) {
return FALSE;
}
else {
return TRUE;
}
} //end email check

And then in my integration code, a simple check

if (UtilitiesDemo.checkEmail (sEmail) ) {
//Use email
}
else {
handle bad email
}

You can see a working example here

Next up, formatting phone numbers from another system…

Leave a Reply