如何用libphonenumber-js按国家码和号码类型获取有效号码长度
用libphonenumber-js获取指定国家和号码类型的有效长度
完全可以实现,直接利用库提供的元数据查询能力就能拿到对应国家、对应类型的有效电话号码数字长度,具体实现步骤如下:
1. 引入库
先通过你提供的CDN地址引入libphonenumber-js:
<script src="https://cdn.jsdelivr.net/npm/libphonenumber-js/bundle/libphonenumber-js.min.js"></script>
2. 编写查询函数
通过getMetadataForCountry获取目标国家的号码规则元数据,再筛选出对应类型的号码长度:
function getValidPhoneLengths(countryCode, phoneType) { // 获取对应国家的元数据,无效国家码直接返回null const countryMetadata = libphonenumber.getMetadataForCountry(countryCode); if (!countryMetadata) return null; // 统一类型格式,匹配库内的常量命名 const standardType = phoneType.toLowerCase() === 'mobile' ? 'MOBILE' : phoneType.toLowerCase() === 'fixed line' ? 'FIXED_LINE' : null; if (!standardType) return null; // 筛选出对应类型的号码格式,提取长度并去重 const validLengths = countryMetadata.formats ?.filter(format => format.types?.includes(standardType)) .map(format => format.length) ?.filter((len, idx, self) => self.indexOf(len) === idx); return validLengths || []; } // 示例调用 console.log(getValidPhoneLengths('AU', 'mobile')); // 输出澳大利亚手机号的有效长度数组 console.log(getValidPhoneLengths('AU', 'fixed line')); // 输出澳大利亚固定电话的有效长度数组
说明
- 函数会返回去重后的有效长度数组,部分国家同类型号码可能存在多种有效长度
- 如果传入无效的国家码或号码类型,函数会返回
null或空数组
内容的提问来源于stack exchange,提问作者Drew
相关产品推荐
相关产品推荐

