Tuesday 24 January 2017

Handle special numbers not handled by libphonenumber.

libphonenumber is Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers. 

Project on GitHub is here - https://github.com/googlei18n/libphonenumber

to add it to your android project use -

 compile 'com.googlecode.libphonenumber:libphonenumber:8.0.1'

Use :

public static boolean isSpecialNumber(PhoneNumber number) {
    if (number.getCountryCode() == 31) {
        // handle special M2M numbers: 11 digits starting with 097[0-8]        
        final Pattern regex = Pattern.compile("^97[0-8][0-9]{8}$");
        Matcher m = regex.matcher(String.valueOf(number.getNationalNumber()));
        return m.matches();
    }
    return false;
}


public void handleSpecialCases(Phonenumber.PhoneNumber phoneNumber) {
    PhoneNumberUtil util = PhoneNumberUtil.getInstance();

    // Argentina numbering rules
    int argCode = util.getCountryCodeForRegion("AR");
    if (phoneNumber.getCountryCode() == argCode) {
        // forcibly add the 9 between country code and national number
        long nsn = phoneNumber.getNationalNumber();
        if (firstDigit(nsn) != 9) {
            phoneNumber.setNationalNumber(addSignificantDigits(nsn, 9));
        }
    }
}

private int firstDigit(long n) {
    while (n < -9 || 9 < n) n /= 10;
    return (int) Math.abs(n);
}

private long addSignificantDigits(long n, int ds) {
    final long orig = n;
    int count = 1;
    while (n < -9 || 9 < n) {
        n /= 10;
        count++;
    }
    long power = ds * (long) Math.pow(10, count);
    return orig + power;
}

1 comment: