Java Program to Validate Phone Numbers using Google's libphonenumber Library
Last Updated :
02 Feb, 2021
Validating phone numbers is a common prerequisite in today’s web, mobile, or desktop applications, but Java does not have an integrated method for carrying out this kind of common validation. So, we have to use some open source libraries to perform such validation. One such library is Google’s phone number library. It helps to verify any phone number, whether foreign, specific to India, or specific to any country.
We can also use regular expressions to validate the phone numbers, but it requires some skills to write such complex expressions and then the testing would be an endless task.
The libphonenumber is an open-source library from Google for formatting, parsing, and validating international phone numbers. It contains many methods to achieve such functionality. Some of them are discussed below:
Return Type
| Method
| Description
|
---|
String |
format(Phonenumber.PhoneNumber number,
PhoneNumberUtil.PhoneNumberFormat numberFormat)
| Uses the default rules to format a phone number in the format specified. |
String | formatNumberForMobileDialing(Phonenumber.PhoneNumber number, java.lang.String regionCallingFrom, boolean withFormatting) | Returns the number in a formatted string such that it can be dialed from a cell phone in that region. |
boolean | isMobileNumberPortableRegion(java.lang.String regionCode) | If the region passed as an argument supports mobile number portability, the method returns true. |
boolean | isNumberMatch(Phonenumber.PhoneNumber firstNumberIn, Phonenumber.PhoneNumber secondNumberIn) | It takes two phone number and checks them for equality |
boolean | isPossibleNumber(java.lang.CharSequence number, java.lang.String regionDialingFrom) | Verify that a telephone number is a possible number given in the form of a string and the region from which the number can be dialed. |
boolean | isValidNumberForRegion(Phonenumber.PhoneNumber number, java.lang.String regionCode) | Checks whether the given number is valid for a particular region |
boolean | isValidNumber(Phonenumber.PhoneNumber number) | Validates whether a phone number matches a specific pattern |
boolean | canBeInternationallyDialled(Phonenumber.PhoneNumber number) | Returns true in case the number can be dialed from outside the specified region |
int | getCountryCodeForRegion(java.lang.String regionCode) | Returns the country calling code for a specific region |
PhoneNumberUtil.PhoneNumberType | getNumberType(Phonenumber.PhoneNumber number) | This method returns the type of number based on the number itself. For example, Toll-Free, Mobile, FixedLine, etc. |
This is a rich library with even more utility features and takes care of much of the needs of our program.
Below is Java Implementation for Validating Phone Numbers using Google's libphonenumber Library. Here we will be using Eclipse IDE.
Step 1: Creating a Maven Project
To begin with first create a Maven Project in Eclipse. The reason behind creating a Maven Project rather than a normal Java Project is that the libphonenumber library is present in the Maven Repository so we have to use it as a dependency in our project.
Leave everything to be the default. The Artifact Id will be the name of your Maven project.
Step 2: Adding the Dependency
Once you have created the Maven Project, add the libphonenumber dependency in the pom.xml file. As soon as you save the file, the library will be downloaded for offline use.
XML
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.Demo</groupId>
<artifactId>DemoProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>8.12.16</version>
</dependency>
</dependencies>
</project>
Step 3: Creating the Driver Class
Now, simply create a Java class to use the functionalities of this library.
Java
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
public class GFG {
public static void main(String args[])
{
// creating an array of random phone numbers
String[] phonenumbers
= { "+91 94483 76473", "1800 425 3800",
"+91 83944 7484", "0294 2424447" };
// iterating over each number to validate
for (String phone : phonenumbers) {
if (isPhoneNumberValid(phone)) {
System.out.println(phone + " is valid.");
}
else {
System.out.println(phone
+ " is not valid.");
}
}
}
// this method return true if the passed phone number is
// valid as per the region specified
public static boolean isPhoneNumberValid(String phone)
{
// creating an instance of PhoneNumber Utility class
PhoneNumberUtil phoneUtil
= PhoneNumberUtil.getInstance();
// creating a variable of type PhoneNumber
PhoneNumber phoneNumber = null;
try {
// the parse method parses the string and
// returns a PhoneNumber in the format of
// specified region
phoneNumber = phoneUtil.parse(phone, "IN");
// this statement prints the type of the phone
// number
System.out.println(
"\nType: "
+ phoneUtil.getNumberType(phoneNumber));
}
catch (NumberParseException e) {
// if the phoneUtil is unable to parse any phone
// number an exception occurs and gets caught in
// this block
System.out.println(
"Unable to parse the given phone number: "
+ phone);
e.printStackTrace();
}
// return the boolean value of the validation
// performed
return phoneUtil.isValidNumber(phoneNumber);
}
}
Output:
Type: MOBILE
+91 94483 76473 is valid.
Type: TOLL_FREE
1800 425 3800 is valid.
Type: UNKNOWN
+91 83944 7484 is not valid.
Type: FIXED_LINE
0294 2424447 is valid.
Similar Reads
Java Program to Check For a Valid Mobile Number In Java, validating mobile numbers is usually done by using Regular Expressions (Regex) that define patterns for matching strings. Mobile number validation can be implemented for both local (Indian) and global phone numbers.Example: Now, let's take a basic example, to check if a mobile number is val
3 min read
Java program to read all mobile numbers present in given file In this article, we are going to discuss a Java program that reads all mobile numbers from a given text file and writes the correct mobile number to another output file. For this, we are going to use regular expression to identify the correct mobile number. Note: The number should meet the correct c
3 min read
How to validate identifier using Regular Expression in Java Given a string str, the task is to check whether the string is a valid identifier or not using the Regular Expression. The valid rules for defining Java identifiers are: It must start with either lower case alphabet[a-z] or upper case alphabet[A-Z] or underscore(_) or a dollar sign($).It should be a
2 min read
How to Match Phone Numbers in a List to a Regex Pattern in Java ? Regular Expressions are also known as regex or regexp. It is one of the powerful features of Java that helps in sequences of characters that define a search pattern. Nowadays it is widely used in computer science, programming, and text processing for tasks such as string matching, data extraction, a
4 min read
Java Program for Phone Mnemonics In our daily lives, we have to remember a lot of phone numbers. Most people find it quite difficult to remember such huge 10-digit phone numbers. A simple solution is to relate that phone number to some known word. For example, we can relate the phone number 32627287 with DAMASCUS based on the chara
4 min read