📜  使用 Google 的 libphonenumber 库验证电话号码的Java程序

📅  最后修改于: 2022-05-13 01:55:26.763000             🧑  作者: Mango

使用 Google 的 libphonenumber 库验证电话号码的Java程序

验证电话号码是当今 Web、移动或桌面应用程序的常见先决条件,但Java没有执行这种常见验证的集成方法。因此,我们必须使用一些开源库来执行此类验证。 Google 的电话号码库就是这样的一个库。它有助于验证任何电话号码,无论是外国的、特定于印度的还是特定于任何国家的。

我们也可以使用正则表达式来验证电话号码,但是编写如此复杂的表达式需要一些技巧,然后测试将是一项无休止的任务。

libphonenumber 是一个来自 Google 的开源库,用于格式化、解析和验证国际电话号码。它包含许多实现此类功能的方法。其中一些讨论如下:

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.
StringformatNumberForMobileDialing(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. 
booleanisMobileNumberPortableRegion(java.lang.String regionCode)If the region passed as an argument supports mobile number portability, the method returns true.
booleanisNumberMatch(Phonenumber.PhoneNumber firstNumberIn, Phonenumber.PhoneNumber secondNumberIn)It takes two phone number and checks them for equality
booleanisPossibleNumber(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.
booleanisValidNumberForRegion(Phonenumber.PhoneNumber number, java.lang.String regionCode)Checks whether the given number is valid for a particular region
booleanisValidNumber(Phonenumber.PhoneNumber number)Validates whether a phone number matches a specific pattern
booleancanBeInternationallyDialled(Phonenumber.PhoneNumber number)Returns true in case the number can be dialed from outside the specified region
intgetCountryCodeForRegion(java.lang.String regionCode)Returns the country calling code for a specific region
PhoneNumberUtil.PhoneNumberTypegetNumberType(Phonenumber.PhoneNumber number)This method returns the type of number based on the number itself. For example, Toll-Free, Mobile, FixedLine, etc.

这是一个具有更多实用功能的丰富库,可以满足我们程序的大部分需求。

下面是使用 Google 的 libphonenumber 库验证电话号码的Java实现。在这里,我们将使用 Eclipse IDE。

步骤 1:创建 Maven 项目

首先在 Eclipse 中创建一个 Maven 项目。创建 Maven 项目而不是普通Java项目的原因是 libphonenumber 库存在于 Maven 存储库中,因此我们必须将其用作项目中的依赖项。




将所有内容保留为默认值。 Artifact Id 将是您的 Maven 项目的名称。

第 2 步:添加依赖项

创建 Maven 项目后,在 pom.xml 文件中添加 libphonenumber 依赖项。保存文件后,库将被下载以供离线使用。

XML

  4.0.0
  com.Demo
  DemoProject
  0.0.1-SNAPSHOT
  
      
        com.googlecode.libphonenumber
        libphonenumber
        8.12.16
      
  


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);
    }
}


步骤 3:创建驱动程序类

现在,只需创建一个Java类即可使用该库的功能。

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);
    }
}

输出:

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.