Phone Formatting in APEX

Another problem we often face when integrating with other systems is formatting phone numbers. If you enter a phone number via the SFDC UI, it will apply standard US phone formatting to the number if it a 10 digits number. But that is being applied by the browser using JS script. If you load data into phone number fields via the API, it leaves them as they are, which doesn’t look great when a user sees the record in the UI, and it can break any phone integrations such as Skype or Google Voice that expect numbers to be formatted in a certain way.

To get round that problem, we can use another utility with a simple REGEX pattern:

public static String formatphonenumber(String cphone) {
String fphone = cphone.replaceAll('\\D','');

if (fphone.length() == 10) {
fphone = formatphonenum(fphone);
return fphone;
}
else {
return cphone;
}

}

static String formatphonenum (String s) {
s = '(' + s.substring(0, 3) + ') ' + s.substring(3, 6) + '-' + s.substring(6);
return s;
}

This one will look at the original string passed to it, remove any character that is not a digit, and if it is 10 digits long, apply the US style phone format to it to make it consistent with the UI formatted numbers.
So if we can do something like this:

String sPhoneRaw = '202-555-1234';
String sPhoneFormatted = UtilitiesDemo.formatphonenumber (sPhoneRaw);
system.assertequals('(202) 555-1234', sPhoneFormatted);

The key line is this one:

String fphone = cphone.replaceAll('\\D','');

replaceall is a standard string function in APEX, but it can use a REGEX as the pattern to search for – in this case, an NON digit. So it doesn’t matter what we get passed from another system/loaded in via the API – we can strip it back to just the digits, and then apply the format if required.

And you can see a working demo here

Leave a Reply