1. Overview
1.概述
In this quick tutorial, we’ll see how to use Google’s open-source library libphonenumber to validate phone numbers in Java.
在这个快速教程中,我们将看到如何使用Google的开源库libphonenumber来验证Java中的电话号码。
2. Maven Dependency
2.Maven的依赖性
First, we’ll need to add the dependency for this library in our pom.xml:
首先,我们需要在pom.xml中添加这个库的依赖性。
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>8.12.10</version>
</dependency>
The latest version information can be found over on Maven Central.
最新的版本信息可以在Maven Central上找到。
Now, we’re equipped to use all the functionality this library has to offer.
现在,我们已经具备了使用这个库所提供的所有功能。
3. PhoneNumberUtil
3.PhoneNumberUtil
The library provides a utility class, PhoneNumberUtil, which provides several methods to play around with phone numbers.
该库提供了一个实用类,PhoneNumberUtil,它提供了几个方法来玩弄电话号码。
Let’s see a few examples of how we can use its various APIs for validation.
让我们看看几个例子,看看我们如何使用其各种API进行验证。
Importantly, in all examples, we’ll be using the singleton object of this class to make method calls:
重要的是,在所有的例子中,我们将使用这个类的单子对象来进行方法调用。
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
3.1. isPossibleNumber
3.1.isPossibleNumber
Using PhoneNumberUtil#isPossibleNumber, we can check if a given number is possible for a particular country code or region.
使用PhoneNumberUtil#isPossibleNumber,我们可以检查某个特定的国家代码或地区的给定号码是否可行。
As an example, let’s take the United States, which has a country code of 1. We can check if given phone numbers are possible US numbers in this fashion:
作为一个例子,我们以美国为例,它的国家代码为1。我们可以通过这种方式检查给定的电话号码是否可能是美国的号码。
@Test
public void givenPhoneNumber_whenPossible_thenValid() {
PhoneNumber number = new PhoneNumber();
number.setCountryCode(1).setNationalNumber(123000L);
assertFalse(phoneNumberUtil.isPossibleNumber(number));
assertFalse(phoneNumberUtil.isPossibleNumber("+1 343 253 00000", "US"));
assertFalse(phoneNumberUtil.isPossibleNumber("(343) 253-00000", "US"));
assertFalse(phoneNumberUtil.isPossibleNumber("dial p for pizza", "US"));
assertFalse(phoneNumberUtil.isPossibleNumber("123-000", "US"));
}
Here, we used another variant of this function as well by passing in the region that we’re expecting the number to be dialed from as a String.
在这里,我们也使用了这个函数的另一个变体,将我们期望拨出的号码的区域作为String传入。
3.2. isPossibleNumberForType
3.2.isPossibleNumberForType
The library recognizes different types of phone numbers, such as fixed-line, mobile, toll-free, voicemail, VoIP, pager, and many more.
该库可识别不同类型的电话号码,如固定电话、移动电话、免费电话、语音信箱、VoIP、传呼机和许多其他。
Its utility method isPossibleNumberForType checks if the given number is possible for a given type in a particular region.
它的实用方法isPossibleNumberForType检查给定的数字在特定区域内对给定类型是否可能。
As an example, let’s go for Argentina since it allows for different possible lengths of numbers for different types.
作为一个例子,让我们选择阿根廷,因为它允许不同类型的数字有不同的可能长度。
Hence, we can use it to demonstrate the capability of this API:
因此,我们可以用它来展示这个API的能力。
@Test
public void givenPhoneNumber_whenPossibleForType_thenValid() {
PhoneNumber number = new PhoneNumber();
number.setCountryCode(54);
number.setNationalNumber(123456);
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
number.setNationalNumber(12345678901L);
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
}
As we can see, the above code validates that Argentina permits 6-digit fixed line numbers and 11-digit mobile numbers.
我们可以看到,上述代码验证了阿根廷允许6位数的固话号码和11位数的手机号码。
3.3. isAlphaNumber
3.3.isAlphaNumber
This method is used to verify if the given phone number is a valid alphanumeric one, such as 325-CARS:
该方法用于验证给定的电话号码是否是一个有效的字母数字号码,如325-CARS。
@Test
public void givenPhoneNumber_whenAlphaNumber_thenValid() {
assertTrue(phoneNumberUtil.isAlphaNumber("325-CARS"));
assertTrue(phoneNumberUtil.isAlphaNumber("0800 REPAIR"));
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE"));
assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE.."));
assertFalse(phoneNumberUtil.isAlphaNumber("+876 1234-1234"));
}
To clarify, a valid alpha number contains at least three digits at the beginning, followed by three or more alphabet letters. The utility method above first strips the given input off any formatting and then checks for this condition.
澄清一下,一个有效的字母数字至少包含三个数字的开头,后面是三个或更多的字母。上面的实用方法首先剥离了给定的输入的任何格式化,然后检查这个条件。
3.4. isValidNumber
3.4.isValidNumber
The previous API we discussed quickly checks the phone number on the basis of its length only. On the other hand, isValidNumber does a complete validation using prefix as well as length information:
我们讨论的前一个API只根据电话号码的长度来快速检查。另一方面,isValidNumber使用前缀和长度信息进行了完整的验证。
@Test
public void givenPhoneNumber_whenValid_thenOK() throws Exception {
PhoneNumber phone = phoneNumberUtil.parse("+911234567890",
CountryCodeSource.UNSPECIFIED.name());
assertTrue(phoneNumberUtil.isValidNumber(phone));
assertTrue(phoneNumberUtil.isValidNumberForRegion(phone, "IN"));
assertFalse(phoneNumberUtil.isValidNumberForRegion(phone, "US"));
assertTrue(phoneNumberUtil.isValidNumber(phoneNumberUtil.getExampleNumber("IN")));
}
Here, the number is validated when we did not specify a region, and also when we did.
在这里,当我们没有指定一个区域时,数字被验证,当我们指定了一个区域时,也被验证。
3.5. isNumberGeographical
3.5.isNumberGeographical
This method checks if a given number has geography or region associated with it:
该方法检查一个给定的数字是否与地理或地区有关。
@Test
public void givenPhoneNumber_whenNumberGeographical_thenValid() throws NumberParseException {
PhoneNumber phone = phoneNumberUtil.parse("+911234567890", "IN");
assertTrue(phoneNumberUtil.isNumberGeographical(phone));
phone = new PhoneNumber().setCountryCode(1).setNationalNumber(2530000L);
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
phone = new PhoneNumber().setCountryCode(800).setNationalNumber(12345678L);
assertFalse(phoneNumberUtil.isNumberGeographical(phone));
}
Here, in the first assert above, we gave the phone number in an international format with the region code, and the method returned true. The second assert uses a local number from the USA, and the third one a toll-free number. So the API returned false for these two.
在这里,在上面的第一个断言中,我们给出了带有地区代码的国际格式的电话号码,该方法返回true。第二个断言使用的是美国的本地号码,第三个断言使用的是免费号码。所以API对这两个返回了false。
4. Conclusion
4.结论
In this tutorial, we saw some of the functionality offered by libphonenumber to format and validate phone numbers using code samples.
在本教程中,我们看到了libphonenumber提供的一些功能,使用代码样本来格式化和验证电话号码。
This is a rich library that offers many more utility functions and takes care of most of our application needs for formatting, parsing, and validating phone numbers.
这是一个丰富的库,提供了更多的实用功能,并照顾到了我们应用程序在格式化、解析和验证电话号码方面的大部分需求。
As always, the source code is available over on GitHub.
一如既往,源代码可在GitHub上获得。