Phone Number Validation in Android: A Complete Guide for Country-Wise Phone Number Length

Learn how to validate phone numbers in Android based on their country codes using Java and the libphonenumber library.

Chintan Joshi

--

Introduction:

Phone number validation is a common requirement for many Android apps, especially those that deal with user registration or login. However, phone numbers can have different formats and lengths depending on their country codes, which makes the validation process more challenging.

Fortunately, there is a solution: the libphonenumber library from Google provides a comprehensive set of tools for phone number validation, formatting, and parsing. In this article, we'll show you how to use the libphonenumber library to validate phone numbers in Android based on their country codes.

Setting Up the libphonenumber Library

The first step is to add the libphonenumber library to your Android project. You can do this by adding the following line to your app’s build.gradle file:

implementation 'com.googlecode.libphonenumber:libphonenumber:8.12.30'

This will download the libphonenumber library and make it available in your project.

Validating Phone Numbers

To validate phone numbers based on their country codes, we’ll create a PhoneNumberValidator class that provides a isValidPhoneNumber method. Here's the code for the PhoneNumberValidator class:

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;

public class PhoneNumberValidator {
private static final PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();
public static boolean isValidPhoneNumber(String countryCode, String phoneNumber) {
try {
Phonenumber.PhoneNumber parsedNumber = PHONE_NUMBER_UTIL.parse(phoneNumber, countryCode);
return PHONE_NUMBER_UTIL.isValidNumber(parsedNumber);
} catch (Exception e) {
return false;
}
}
}

In this implementation, the isValidPhoneNumber method takes two arguments: the country code (e.g., "+91" for India) and…

--

--

Chintan Joshi

Android developer. Proficient in Java/Kotlin. Passionate about creating user-friendly apps. Constantly exploring new tech. Open-source contributor.