10分钟学会使用libphonenumber-js:从零开始的电话号码处理教程

【免费下载链接】libphonenumber-js A simpler (and smaller) rewrite of Google Android's libphonenumber library in javascript 【免费下载链接】libphonenumber-js 项目地址: https://gitcode.com/gh_mirrors/li/libphonenumber-js

libphonenumber-js是一个轻量级的JavaScript库,用于解析、验证和格式化电话号码,是Google Android系统中libphonenumber库的简化重写版本。它体积小巧但功能强大,非常适合在Web应用中处理用户输入的电话号码。

🚀 快速安装:30秒上手

使用npm或yarn即可快速安装libphonenumber-js:

# 使用npm安装
npm install libphonenumber-js --save

# 或使用yarn安装
yarn add libphonenumber-js

如果需要更严格的号码验证或号码类型检测功能,可以安装包含完整元数据的版本:

# 完整功能版(包含号码类型检测)
npm install libphonenumber-js/max --save

📱 核心功能:电话号码处理四步走

1️⃣ 解析电话号码

解析功能可以从字符串中提取有效的电话号码信息,支持国际号码和带默认国家的本地号码:

import parsePhoneNumber from 'libphonenumber-js'

// 解析国际号码
const number = parsePhoneNumber('+12133734253')
console.log(number.country) // "US"
console.log(number.number)  // "+12133734253"

// 解析本地号码(需指定默认国家)
const number = parsePhoneNumber('(213) 373-4253', 'US')
console.log(number.formatInternational()) // "+1 213 373 4253"

2️⃣ 格式化电话号码

支持多种格式输出,满足不同场景需求:

import parsePhoneNumber from 'libphonenumber-js'

const number = parsePhoneNumber('+12133734253')

// 国际格式
console.log(number.formatInternational()) // "+1 213 373 4253"

// 本地格式
console.log(number.formatNational())      // "(213) 373-4253"

// E.164格式(适合存储)
console.log(number.format('E.164'))       // "+12133734253"

// 电话URI格式(适合<a href>链接)
console.log(number.getURI())              // "tel:+12133734253"

3️⃣ 实时输入格式化

"As You Type"功能可以在用户输入时实时格式化电话号码,提升用户体验:

import { AsYouType } from 'libphonenumber-js'

// 美国号码实时格式化
const formatter = new AsYouType('US')
console.log(formatter.input('2133734253')) // "(213) 373-4253"

// 国际号码实时格式化
const formatter = new AsYouType()
console.log(formatter.input('+12133734253')) // "+1 213 373 4253"

4️⃣ 验证电话号码

提供两种验证级别,满足不同需求:

import { isPossiblePhoneNumber, isValidPhoneNumber } from 'libphonenumber-js'

// 基础验证(仅检查长度)
console.log(isPossiblePhoneNumber('(213) 373-4253', 'US')) // true

// 严格验证(检查格式和有效性)
console.log(isValidPhoneNumber('(213) 373-4253', 'US'))    // true
console.log(isValidPhoneNumber('(111) 111-1111', 'US'))    // false

💡 实用技巧:提升开发效率

从文本中提取电话号码

自动识别文本中的所有电话号码,适用于数据挖掘和内容分析:

import { findPhoneNumbersInText } from 'libphonenumber-js'

const text = `联系我们:+86 10 1234 5678 或 (021) 5555-8888`
const numbers = findPhoneNumbersInText(text, 'CN')

numbers.forEach(result => {
  console.log(result.number.formatInternational())
})
// 输出:
// +86 10 1234 5678
// +86 21 5555 8888

元数据选择:平衡功能与体积

库提供不同量级的元数据,可根据项目需求选择:

  • 默认版 (libphonenumber-js):80KB,基础功能,适合大多数场景
  • 完整版 (libphonenumber-js/max):145KB,包含号码类型检测和严格验证
  • 移动版 (libphonenumber-js/mobile):95KB,仅支持移动号码验证
// 使用完整版元数据检测号码类型
import parsePhoneNumber from 'libphonenumber-js/max'

const number = parsePhoneNumber('+18005551234')
console.log(number.getType()) // "TOLL_FREE"

🛠️ 实际应用:表单验证示例

结合HTML表单实现实时电话号码验证:

<input type="tel" id="phone" placeholder="输入电话号码">
<div id="error" style="color: red;"></div>

<script type="module">
  import { AsYouType, isValidPhoneNumber } from 'libphonenumber-js'
  
  const input = document.getElementById('phone')
  const error = document.getElementById('error')
  const formatter = new AsYouType('CN')
  
  input.addEventListener('input', () => {
    const formatted = formatter.input(input.value)
    input.value = formatted
    
    // 验证号码
    if (formatted) {
      const valid = isValidPhoneNumber(formatted, 'CN')
      error.textContent = valid ? '✅ 号码有效' : '❌ 请输入有效的中国电话号码'
      error.style.color = valid ? 'green' : 'red'
    } else {
      error.textContent = ''
    }
  })
</script>

📚 资源与扩展

  • 完整API文档:可在项目源码中的source/目录查看各模块实现
  • 测试示例test/目录包含大量测试用例,可作为使用参考
  • React组件:推荐使用react-phone-number-input,基于libphonenumber-js构建的React电话号码输入组件

通过这篇教程,你已经掌握了libphonenumber-js的核心功能。这个轻量级库可以帮助你轻松处理各种电话号码相关任务,从解析、验证到格式化,满足Web应用中的常见需求。无论是简单的表单验证还是复杂的号码处理,libphonenumber-js都能提供可靠的支持。

要开始使用,只需执行npm install libphonenumber-js,然后按照示例代码集成到你的项目中即可。祝你的电话号码处理功能开发顺利!

【免费下载链接】libphonenumber-js A simpler (and smaller) rewrite of Google Android's libphonenumber library in javascript 【免费下载链接】libphonenumber-js 项目地址: https://gitcode.com/gh_mirrors/li/libphonenumber-js

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐