In case you want to use E164 format - here's a utility method I wrote a while back. Adapt as required. YMMV
/** -----------------------------------------------------------------
* toE164 : Normalizes phone number to E.164 format somestring.toE164(String countryCode)
* Ideal solution would be an Apex port of Google libphonenumber but this is a huge library
* We'll do simple stuff, stripping out noise characters, extensions and adding back the country code
* Custom metadata
* could be used but for batch performance, static maps for now.
* If the number is not recognizable, unsupported country or too short, return asis.
*
* Converts (650)555-1212 to +16505551212
* Converts +44 (020) 88.99.11.22 to +442088991122
**/
private class NationalPhoneNature {
String countryCode;
Integer minLen;
Integer maxLen;
String trunkCode;
NationalPhoneNature withCountryCode(String val) {this.countryCode = val; return this;}
NationalPhoneNature withMinLen(Integer val) {this.minLen = val; return this;}
NationalPhoneNature withMaxLen(Integer val) {this.maxLen = val; return this;}
NationalPhoneNature withTrunkCode(String val) {this.trunkCode = val; return this;}
}
private static final Map<String,NationalPhoneNature> NATIONAL_PHONE_NATURES_BY_COUNTRY_CODE = new Map<String,NationalPhoneNature> {
'CA' => new NationalPhoneNature().withCountryCode('1').withMinLen(10).withMaxLen(10).withTrunkCode('1'),
'MX' => new NationalPhoneNature().withCountryCode('1').withMinLen(10).withMaxLen(10).withTrunkCode('1'),
'UK' => new NationalPhoneNature().withCountryCode('44').withMinLen(9).withMaxLen(10).withTrunkCode('0'),
'US' => new NationalPhoneNature().withCountryCode('1').withMinLen(10).withMaxLen(10).withTrunkCode('1')
};
public static String toE164(String phoneNum) {
return toE164(phoneNum, 'US');
}
public static String toE164(String phoneNum, String isoCountryCode) {
if (phoneNum == null) return null;
if (!NATIONAL_PHONE_NATURES_BY_COUNTRY_CODE.containsKey(isoCountryCode)) return phoneNum; // not supported
String phonePure = phoneNum.replaceAll('[^0-9]',''); // strip noise chars, leading +, etc.
NationalPhoneNature nature = NATIONAL_PHONE_NATURES_BY_COUNTRY_CODE.get(isoCountryCode);
// Strip off country code, if any
if (phonePure.startsWith(nature.countryCode)) {
phonePure = phonePure.substring(nature.countryCode.length());
}
// Strip off trunk code, if any
if (phonePure.startsWith(nature.trunkCode)) {
phonePure = phonePure.substring(nature.trunkCode.length());
}
// Check what we have left to see if workable
if (phonePure.length() < nature.minLen) {
return phoneNum;
}
// If greater than max length, assume excess is an extension (not supported here)
if (phonePure.length() > nature.maxLen) {
phonePure = phonePure.substring(0,nature.maxLen);
}
return '+' + nature.countryCode + phonePure;
}