Android: Validate Phone Number Length by COUNTRY

6.3k views Asked by At

How can we validate the length of a mobile number by COUNTRY? (Knowing that the country code might or might not be part of the number)

Length may vary per country, meaning there should be a length range or pattern validator.

Example:

  • +1 222 2222 222 (13 digits) Valid ✔️
  • 222 2222 222 (12 digits) Valid only if chosen in corresponding Locale ✔️
  • +1 222 2222 2222222 (17 digits) Invalid ❌
  • +1 222 2222 (8 digits) Invalid ❌

Note: Any idea where can I find each country's mobile number length range.

Thank you!

3

There are 3 answers

1
Lance Samaria On BEST ANSWER

Kotlin answer

val swissNumberStr = "044 668 18 00"
val phoneUtil = PhoneNumberUtil.getInstance()

try {

    val swissNumberPrototype = phoneUtil.parse(swissNumberStr, "CH")

    val isValid = phoneUtil.isValidNumber(swissNumberPrototype)

    if (isValid) {
        // do something
    } else {
        // do something else
    }

} catch (e: NumberParseException) {
    System.err.println("NumberParseException was thrown: $e")
}
1
Zain On

Given the mobile number and the country code, you can use libphonenumeer which is a Google library for validating phone numbers; it checks the number length and catches NumberParseException exception if it is not a right number.

This is their sample in how to use it

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}
0
Charlie Abou Moussa On

Adding to @Zain 's answer.

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
//  This will check if the phone number is real and its length is valid.
  boolean isPossible = phoneUtil.isPossibleNumber(swissNumberProto);
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}