Created
October 7, 2016 12:43
-
-
Save dominicthomas/b189e7a07eea62d17c0da64fd48a40dc to your computer and use it in GitHub Desktop.
Simple class to format and convert to E164, mobile phone numbers for the UK and the US.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PhoneNumberFormatter { | |
private final String simCountryIso; | |
private final Map<String, String> countryCodeMap = Collections.unmodifiableMap( | |
new HashMap<String, String>() {{ | |
put("GB", "44"); | |
put("US", "1"); | |
}}); | |
private final Map<String, String> countryPatternMap = Collections.unmodifiableMap( | |
new HashMap<String, String>() {{ | |
put("GB", "^(\\+44\\s?7\\d{9}|\\(?07\\d{9}\\)?)"); | |
put("US", "^([\\+][1]{1})?\\(?([2-9]{3})\\)?([0-9]{3})([0-9]{4})$"); | |
}}); | |
public static PhoneNumberFormatter init(Context context) { | |
final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
return new PhoneNumberFormatter(telephonyManager.getSimCountryIso().toUpperCase()); | |
} | |
public PhoneNumberFormatter(String simCountryIso) { | |
this.simCountryIso = simCountryIso; | |
} | |
public Optional<String> getFormattedPhoneNumber(String phoneNumber) { | |
if (phoneNumber == null || simCountryIso == null) { | |
return Optional.absent(); | |
} | |
phoneNumber = phoneNumber.replaceAll("\\s+", ""); | |
if (!isValid(phoneNumber, simCountryIso)) { | |
return Optional.absent(); | |
} | |
if (!countryCodeMap.containsKey(simCountryIso)) { | |
return Optional.absent(); | |
} | |
final String dialingCode = countryCodeMap.get(simCountryIso); | |
final boolean startsWithCountryCode = phoneNumber.startsWith("+" + dialingCode); | |
final boolean startsWithZero = phoneNumber.startsWith("0"); | |
if (!startsWithCountryCode && !startsWithZero) { | |
final String formattedString = "+" + dialingCode + phoneNumber; | |
return Optional.of(formattedString); | |
} else if (!startsWithCountryCode) { | |
final String numberWithoutFirstDigit = phoneNumber.substring(1, phoneNumber.length()); | |
final String formattedString = "+" + dialingCode + numberWithoutFirstDigit; | |
return Optional.of(formattedString); | |
} | |
if (!phoneNumber.startsWith("+")) { | |
phoneNumber = "+" + phoneNumber; | |
} | |
return Optional.of(phoneNumber); | |
} | |
private boolean isValid(String phoneNumber, String simCountryIso) { | |
if (!countryPatternMap.containsKey(simCountryIso)) { | |
return false; | |
} | |
final String pattern = countryPatternMap.get(simCountryIso); | |
return Pattern.compile(pattern).matcher(phoneNumber).matches(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment