How to validate phone number in Java? Google libphonenumber library Example Tutorial

It's a common requirement to validate phone numbers for a Java web application, much like validating email addresses. Unfortunately, Java doesn't provide any built-in method to carry out this kind of common validation, I would love to have a validation package in Java, but don't worry there must be an open-source library to cover this deficiency, right? Yes, there is Google's phone number library which allows you to validate any phone number both international, USA specific or any country-specific.


So forget about writing a complex regular expression, testing it endlessly only to realize that certain valid phone numbers are not matching and if you get it right then tweaking it endlessly to validate another country's phone number.

I always try to follow Java guru Joshua Bloch's advice by hearing, use a library method instead of writing your own for production code, and my argument is testing. You would never be able to test a common utility method like validating phone numbers or email addresses as thoroughly by yourself as in case of open source library, forget about the constant time pressure you have to deliver the main functionality.

Btw, if you are new to Java world then I recommend you to go through a comprehensive Java course like The Complete Java Masterclass on Udemy, which is not just a very comprehensive but also most up-to-date course and covers recent Java features.




Google's libphonenumber library

The libphonenumber is Google's open-source library for parsing, formatting, validating and storing international phone numbers. The Java version is also optimized for running on smartphones and is used by the Android framework since 4.0 (Ice Cream Sandwich). Now, let's see what you can do with this wonderful utility library from Google :

1) You can parse, format and validate phone numbers from any country or region in the world.

2) You can find which type of phone number you are dealing with by calling method getNumberType(). This method allows you to find the type of the number based on the number itself; allow you to distinguish between Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP and Personal Numbers (whenever feasible).

3) Allow you to check if two phone numbers are the same by using the isNumberMatch() method.

4) You can find geographical information related to phone numbers like which country, which region by using the PhoneNumberOfflineGeocoder method.

How to validate phone number in Java?



Java Program to validate Phone numbers

Now, let's see a real-world code example of how to validate phone numbers in Java

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

/**
 * This class demonstrate how to validated and format phone numbers using
 * Google's libphonenumber library.
 */
public class PrimeNumberGenerator {

    public static void main(String args[]) {
        String[] numbers = { "+91 94483 76473", "+1 303 230340",
                "+91 83944 7484", "091 93328 23484" };

        for (String phone : numbers) {
            if (isPhoneNumberValid(phone)) {
                System.out.printf("%s is valid %n", phone);
            }else {
                System.err.printf("%s is not valid %n", phone);
            }
        }

    }

    /**
     * Java method to validate phone number
     * @param phoneStr
     * @return true if given phone number is valid
     */
    public static boolean isPhoneNumberValid(String phoneStr) {
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        PhoneNumber thePhoneNumber = null; // The class which represent
                                           // a phone number
        try {
            thePhoneNumber = phoneUtil.parse(phoneStr, "IN");
        } catch (NumberParseException e) {
            System.err.println("Cannot parse the given phone number string "
                    + phoneStr);
            e.printStackTrace();
        }

        // Now, let's validate phone number
        return phoneUtil.isValidNumber(thePhoneNumber);
    }
}

Output :
+91 94483 76473 is valid 
+1 303 230340 is not valid 
+91 83944 7484 is not valid 
091 93328 23484 is not valid 



You can see that only the valid phone numbers are judged valid, others are invalid. You can even use this library to format phone numbers in an international or national format.

That's all about how to validate phone numbers in Java using Google's libphonenumber library. If you find this example useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.I also recommend you to check my article about 20 essential libraries Java developer should know to learn more about such gems which can save your day and also make you a better Java developer.

Further Learning

133 Core Java Interview Questions from last 5 years
101 Coding Problems and few tips for Job Interviews
Grokking the Coding Interview: Patterns for Coding Questions


P. S. - If you are new to Java world and looking for some free resources to kick-start your Java development journey, then I also suggest you check out this list of free Java courses for beginners on Medium. 

2 comments:

  1. couldn't find getInstance method after PhoneNumberUtil

    ReplyDelete
    Replies
    1. It's actually inside the library, do you have correct JAR file in classpath?

      Delete

Feel free to comment, ask questions if you have any doubt.