Reputation: 1175
How do I use Google's libphone number https://github.com/googlei18n/libphonenumber to see if a phone number is Canada's or US' phone number as they share the same country code?
example: +1415-555-0123 is U.S., San Francisco +1647-555-0123 is Canada, Toronto
Just by providing a phone number I need to get the country name.
When I tried something like the following, it returned "true" whereas my expectation is that it should have returned false as the phone number is not a US number but a Canada number.
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
boolean isPossible = phoneUtil.isPossibleNumber("+16475550123", "US");
Upvotes: 5
Views: 6470
Reputation: 1175
I realized that it is a 2-step process:
Step 1: (First check if it's a possible number)
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
boolean isPossible = phoneUtil.isPossibleNumber("+16475550123", "US");
Step 2: (Then check if it is valid for region)
Phonenumber.PhoneNumber number = phoneUtil.parse("+16475550123", "US");
isValid = phoneUtil.isValidNumberForRegion(number, "US");
//isValid is false as 647 is not a US area code.
We can have something like this:
String countries[] = {"US", "CA"};
String phoneNumber = "+13101234567";
for (String c : countries) {
boolean isValid = phoneUtil.isPossibleNumber(phoneNumber, c);
if (isValid) {
try {
Phonenumber.PhoneNumber number = phoneUtil.parse(phoneNumber, c);
isValid = phoneUtil.isValidNumberForRegion(number, c);
if(isValid) {
System.out.println("Country is " + c);
}
}catch(Exception e) {}
}
}
Upvotes: 3
Reputation: 2783
You may be looking for PhoneNumberUtil.isValidNumberForRegion()
. From its documentation, it
Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number.
Upvotes: 1