androidvalidationphone-numbertelephonymobile-country-code

Android: Validate Phone Number Length by COUNTRY


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:

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

Thank you!


Solution

  • 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")
    }