Google libphonenumber to validate phone number of all regions across the world - Java @ Desk

Saturday, November 23, 2013

Google libphonenumber to validate phone number of all regions across the world

Google libphonenumber to validate phone number of all regions across the world
Google has provided a jar libphonenumber.jar using which any number across the world from any country can be validated.

You can download the jar from this location - https://code.google.com/p/libphonenumber/
User interface for testing purpose - http://libphonenumber.appspot.com/
Specify any phone number and you will recieve all the details of the phone number
Functionality provided:
1) Parsing/formatting/validating phone numbers for all countries/regions of the world.
2) getRegionCodeForNumber() method gives the country of the provided phone number
3) isValidNumber - full validation of a phone number for a region using length and prefix information.

Sample implementation is shown below

 package test;  
 import com.google.i18n.phonenumbers.NumberParseException;  
 import com.google.i18n.phonenumbers.PhoneNumberUtil;  
 import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;  
 public class ValidatePhoneNumber {  
      public static void main(String args[]) {  
           String number = "+91XXXXXXX";  
           PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();  
           try {  
                PhoneNumber numberProto = phoneUtil.parse(number, "");  
                System.out.println("Number is of region - "  
                          + phoneUtil.getRegionCodeForNumber(numberProto));  
                System.out  
                          .println("Is the input number valid - "  
                                    + (phoneUtil.isValidNumber(numberProto) == true ? "Yes"  
                                              : "No"));  
           } catch (NumberParseException e) {  
                System.err.println("NumberParseException was thrown: "  
                          + e.toString());  
           }  
      }  
 }  

Output is for number +91XXXXXX

Number is of region - IN
Is the input number valid - Yes

For invalid number 91XXXXXX

NumberParseException was thrown: Error type: INVALID_COUNTRY_CODE. Missing or invalid default region.







No comments:

Post a Comment