It is possible to check if a given string represents a valid phone number, using this code, together with the PhoneNumberUtil library by Google (available here) :
public static boolean isValidNumber(final PhoneNumber phone) {
if (phone == null)
return false;
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
return phoneNumberUtil.isValidNumber(phone);
}
public static boolean isValidPhoneNumber(String phone) {
if (TextUtils.isEmpty(phone))
return false;
phone = phone.replaceAll("[^0-9]", "");
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = null;
try {
phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
} catch (final Exception e) {
}
return isValidNumber(phoneNumber);
}
This is only a general check, but I can't find out if it's possible to know if the phone number is actually of a mobile device.
As I've read in some websites, the above check might need to have just a small adjustment to know if it's of a mobile device, but according to my tests, it's wrong :
...
phone = phone.replaceAll("[^0-9]", "");
if (phone.length() < 7)
return false;
...
Is it possible to know if the phone number is of a mobile device?
If so, how ?
Seems I've missed the function in the library. Here's how to do it:
public static boolean isValidMobileNumber(String phone) {
if (TextUtils.isEmpty(phone))
return false;
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber phoneNumber = phoneNumberUtil.parse(phone, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
return phoneNumberType == PhoneNumberUtil.PhoneNumberType.MOBILE;
} catch (final Exception e) {
}
return false;
}
EDIT: it seems some numbers (in the US and a few others ) cannot be determined whether they are of mobile phones or not. In this case, FIXED_LINE_OR_MOBILE is returned.
If you still need to know if the phone number is mobile, there are online services to check it out (though they can't know all, of course), such as Pathfinder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With