需求:验证各个国家地区手机号码是否正确:
规则:
香港: 国家码为852,手机号规则: 首位为5|6|8|9 后面接7位数字,一共8位数。
台湾:国家码为886 ,手机号规则: 首位为9|09 后面接8位数字。一个9位或10位数字。
澳门:国家码为853,手机号规则: 首位为6 后面接7位数字,一个8位数。
google提供了一个开源库,供我们验证各地区手机号。
库地址:https://github.com/googlei18n/libphonenumber
使用方式:
1.下载:libphonenumber-7.2.2.jar
下载地址:https://download.csdn.net/download/yhy123456q/11012130
2.添加依赖:
implementation files('libs/libphonenumber-7.2.2.jar')3.使用
/** * 根据区号判断是否是正确的电话号码 * * @param countryCode :默认国家码 *return :true 合法 false:不合法 * @paramphoneNumber :带国家码的电话号码 */public static boolean isPhoneNumberValid(String phoneNumber, String countryCode) {System.out.println("isPhoneNumberValid: " + phoneNumber + "/" + countryCode);PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();try {Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNumber, countryCode);return phoneUtil.isValidNumber(numberProto);} catch (NumberParseException e) {System.err.println("isPhoneNumberValid NumberParseException was thrown: " + e.toString());}return false;}4.测试
/** * 检查世界各地区国家的手机号码是否正确 * 格式:国家码 86 手机号 +8618800183546 * @param view */public void checkPhone(View view) {String countryCode = et_country_code.getText().toString().trim();String phoneNo = et_phone_no.getText().toString().trim();Log.i("YHY", "checkPhone: " + isPhoneNumberValid(phoneNo, countryCode));}