@foodhubglobal/电话
电话解析、格式化和验证 手机号码-js,带有TypeScript类型和双重通用JS/ES模块构建.
运行 JavaScript 的任何地方 — React Introduct, React, Node.js 和浏览器. 该包没有反应或反应原生依赖.
安装
npm install @foodhubglobal/phone
# or
yarn add @foodhubglobal/phone
不同环境中的使用
这个库可兼容多个JavaScript/TypeScript环境. 电话模块是一个在任何JavaScript运行时间中工作的纯公用库.
1. 反应原生应用程序
// App.tsx or any component file
import {
formatPhoneNumber,
validatePhoneNumber,
formatAsYouType
} from '@foodhubglobal/phone';
// Usage in React Native component
import React, { useState } from 'react';
import { TextInput, View, Text } from 'react-native';
function PhoneInput() {
const [phone, setPhone] = useState('');
return (
<View>
<TextInput
value={phone}
onChangeText={(text) => setPhone(formatAsYouType(text, 'US'))}
placeholder="Enter phone number"
/>
{validatePhoneNumber(phone, 'US') && (
<Text>Formatted: {formatPhoneNumber(phone, 'US')}</Text>
)}
</View>
);
}
2. react.js (网页应用程序)
// Component.tsx or any React component
import {
formatPhoneNumber,
validatePhoneNumber,
formatAsYouType
} from '@foodhubglobal/phone';
// Usage in React component
import React, { useState } from 'react';
function PhoneInput() {
const [phone, setPhone] = useState('');
return (
<div>
<input
type="tel"
value={phone}
onChange={(e) => setPhone(formatAsYouType(e.target.value, 'US'))}
placeholder="Enter phone number"
/>
{validatePhoneNumber(phone, 'US') && (
<p>Formatted: {formatPhoneNumber(phone, 'US')}</p>
)}
</div>
);
}
3. 节点js(API/服务层)
普通JS( 必需)
// server.js or api.js
const {
formatPhoneNumber,
validatePhoneNumber,
parsePhone
} = require('@foodhubglobal/phone');
// Usage in Express.js API route
const express = require('express');
const app = express();
app.post('/validate-phone', (req, res) => {
const { phone, country } = req.body;
if (validatePhoneNumber(phone, country)) {
const formatted = formatPhoneNumber(phone, country);
res.json({ valid: true, formatted });
} else {
res.status(400).json({ valid: false, error: 'Invalid phone number' });
}
});
// Usage with detailed parsing
app.get('/parse-phone/:phone', (req, res) => {
const result = parsePhone(req.params.phone, req.query.country);
res.json(result);
});
ES模块(进口) - 节点.js 12+或有"类型":"模块"
// server.mjs or package.json has "type": "module"
import {
formatPhoneNumber,
validatePhoneNumber,
parsePhone
} from '@foodhubglobal/phone';
// Usage in Express.js API route (ES Modules)
import express from 'express';
const app = express();
app.post('/validate-phone', (req, res) => {
const { phone, country } = req.body;
if (validatePhoneNumber(phone, country)) {
const formatted = formatPhoneNumber(phone, country);
res.json({ valid: true, formatted });
} else {
res.status(400).json({ valid: false, error: 'Invalid phone number' });
}
});
节点.js中的脚本类型
// api.ts or server.ts
import {
formatPhoneNumber,
validatePhoneNumber,
parsePhone,
type CountryCode
} from '@foodhubglobal/phone';
// Usage in Express.js API route (TypeScript)
import express, { Request, Response } from 'express';
const app = express();
app.post('/validate-phone', (req: Request, res: Response) => {
const { phone, country }: { phone: string; country?: CountryCode } = req.body;
if (validatePhoneNumber(phone, country)) {
const formatted = formatPhoneNumber(phone, country);
res.json({ valid: true, formatted });
} else {
res.status(400).json({ valid: false, error: 'Invalid phone number' });
}
});
4. 纯JavaScript项目(浏览器/Vanilla JS)
HTML 有脚本标记 (浏览器)
<!-- Note: You'll need to bundle this first or use a CDN/bundler -->
<!DOCTYPE html>
<html>
<head>
<title>Phone Formatter</title>
</head>
<body>
<input type="tel" id="phoneInput" placeholder="Enter phone number">
<button onclick="formatPhone()">Format</button>
<p id="result"></p>
<script type="module">
// If using ES modules in browser
import { formatPhoneNumber, validatePhoneNumber } from './node_modules/@foodhubglobal/phone/lib/module/index.js';
window.formatPhone = function() {
const input = document.getElementById('phoneInput');
const result = document.getElementById('result');
const phone = input.value;
if (validatePhoneNumber(phone, 'US')) {
result.textContent = `Formatted: ${formatPhoneNumber(phone, 'US')}`;
} else {
result.textContent = 'Invalid phone number';
}
};
</script>
</body>
</html>
Bundled JavaScript (Webpack/Rollup/Vite) (中文(简体) )
// app.js - Works with any bundler (Webpack, Rollup, Vite, etc.)
import {
formatPhoneNumber,
validatePhoneNumber
} from '@foodhubglobal/phone';
// Usage
function formatPhone(phoneNumber) {
if (validatePhoneNumber(phoneNumber, 'US')) {
return formatPhoneNumber(phoneNumber, 'US');
}
return 'Invalid phone number';
}
// Export for use in other files
export { formatPhone };
节点.js 脚本(CLI/Tooling)
// script.js - Run with: node script.js
const { formatPhoneNumber, validatePhoneNumber } = require('@foodhubglobal/phone');
// CLI usage
const phoneNumber = process.argv[2];
const country = process.argv[3] || 'US';
if (validatePhoneNumber(phoneNumber, country)) {
console.log(`Valid! Formatted: ${formatPhoneNumber(phoneNumber, country)}`);
} else {
console.log('Invalid phone number');
process.exit(1);
}
模块
电话模块
顶部建有综合电话号码格式化和验证模块 libphonenumber-js. 为世界各地的电话号码格式化、验证和解析提供公用事业.
安装
电话模块包含在主包中. 不需要额外安装.
使用量
import {
formatPhoneNumber,
formatInternational,
validatePhoneNumber,
formatAsYouType
} from '@foodhubglobal/phone';
实例
格式化电话号码
import { formatPhoneNumber, formatInternational, formatNational } from '@foodhubglobal/phone';
// E.164 format (default)
// With country code parameter (recommended for national numbers)
formatPhoneNumber('2125551234', 'US'); // => '+12125551234'
// Without country code (works when number includes country prefix)
formatPhoneNumber('+12125551234'); // => '+12125551234'
formatPhoneNumber('+442071234567'); // => '+442071234567'
// Fallback: Without country code for national number (returns original phoneNumber)
formatPhoneNumber('2125551234'); // => '2125551234' (returns original if parsing fails)
// With fallback parameter
formatPhoneNumber('invalid', undefined, 'N/A'); // => 'N/A' (returns fallback)
formatPhoneNumber('invalid'); // => 'invalid' (returns original phoneNumber)
// International format
formatInternational('2125551234', 'US'); // => '+1 212 555 1234'
formatInternational('02071234567', 'GB'); // => '+44 20 7123 4567'
formatInternational('+12125551234'); // => '+1 212 555 1234'
formatInternational('invalid', undefined, 'N/A'); // => 'N/A' (returns fallback)
// National format
formatNational('2125551234', 'US'); // => '(212) 555-1234'
formatNational('02071234567', 'GB'); // => '020 7123 4567'
formatNational('+12125551234'); // => '(212) 555-1234'
formatNational('invalid', undefined, 'N/A'); // => 'N/A' (returns fallback)
重要内容: 国家编号(没有国家代码前缀,例如: +1,总是提供 countryCode 精确结果参数.
处理错误 : 现在所有格式函数都支持可选 fallback 参数。 如果解析失败 :
- 与
fallback备注:返回fallback价值 - 无
fallback: 返回原始内容phoneNumber(用于格式函数)或undefined(用于提取/元件函数)
验证电话号码
import { validatePhoneNumber, isPossibleNumber } from '@foodhubglobal/phone';
validatePhoneNumber('+12125551234'); // => true
validatePhoneNumber('2125551234', 'US'); // => true
validatePhoneNumber('123', 'US'); // => false
isPossibleNumber('2125551234', 'US'); // => true
isPossibleNumber('123', 'US'); // => false
A -- You- Type 格式化
import { formatAsYouType } from '@foodhubglobal/phone';
// With country code parameter (recommended)
formatAsYouType('212', 'US'); // => '(212)'
formatAsYouType('212555', 'US'); // => '(212) 555'
formatAsYouType('2125551234', 'US'); // => '(212) 555-1234'
// Without country code (works when input includes country prefix)
formatAsYouType('+1212'); // => '+1 212'
formatAsYouType('+442071234567'); // => '+44 20 7123 4567'
// Use in TextInput for real-time formatting
<TextInput
value={phoneNumber}
onChangeText={(text) => setPhoneNumber(formatAsYouType(text, 'US'))}
/>
解析电话号码
import { parsePhone } from '@foodhubglobal/phone';
// With country code parameter (recommended for national numbers)
const result1 = parsePhone('2125551234', 'US');
// => {
// isValid: true,
// isPossible: true,
// country: 'US',
// countryCallingCode: '1',
// nationalNumber: '2125551234',
// internationalFormat: '+1 212 555 1234',
// nationalFormat: '(212) 555-1234',
// e164Format: '+12125551234'
// }
// Without country code (works when number includes country prefix)
const result2 = parsePhone('+12125551234');
// => { ... same structure as above ... }
// Fallback: Without country code for national number (returns error object)
const result3 = parsePhone('2125551234');
// => {
// isValid: false,
// isPossible: false
// }
获取国家信息
import {
getCountryFromPhoneNumber,
getCallingCode,
getAvailableCountries
} from '@foodhubglobal/phone';
getCountryFromPhoneNumber('+12125551234'); // => 'US'
getCountryFromPhoneNumber('+442071234567'); // => 'GB'
getCountryFromPhoneNumber('invalid', 'US'); // => 'US' (returns fallback)
getCallingCode('US'); // => '1'
getCallingCode('GB'); // => '44'
getCallingCode('IN'); // => '91'
getCallingCode('INVALID', 'N/A'); // => 'N/A' (returns fallback)
getAvailableCountries(); // => ['US', 'GB', 'CA', 'AU', 'IN', ...]
提取电话号码
import { extractPhoneNumber } from '@foodhubglobal/phone';
extractPhoneNumber('Call me at +12125551234'); // => '+12125551234'
extractPhoneNumber('2125551234', 'US'); // => '+12125551234'
extractPhoneNumber('No phone here', undefined, 'N/A'); // => 'N/A' (returns fallback)
extractPhoneNumber('No phone here'); // => undefined (no fallback provided)
数字类型检测
import {
getNumberType,
isMobileNumber,
isFixedLineNumber
} from '@foodhubglobal/phone';
getNumberType('+12125551234'); // => 'MOBILE' | 'FIXED_LINE' | 'VOIP' | etc.
isMobileNumber('+12125551234'); // => true | false
isFixedLineNumber('+12125551234'); // => true | false
额外水电费
import {
normalizePhoneNumber,
formatIncomplete,
getNationalNumber,
getCallingCodeFromNumber,
isSameNumber,
isValidForCountry,
formatRFC3966,
format
} from '@foodhubglobal/phone';
// Normalize phone number
normalizePhoneNumber('(212) 555-1234', 'US'); // => '+12125551234'
normalizePhoneNumber('invalid', undefined, 'N/A'); // => 'N/A' (returns fallback)
// Format incomplete numbers
formatIncomplete('212', 'US'); // => '(212)'
// Get national number
getNationalNumber('+12125551234'); // => '2125551234'
getNationalNumber('invalid', undefined, 'N/A'); // => 'N/A' (returns fallback)
getNationalNumber('invalid'); // => undefined (no fallback provided)
// Get calling code from number
getCallingCodeFromNumber('+12125551234'); // => '1'
getCallingCodeFromNumber('invalid', 'N/A'); // => 'N/A' (returns fallback)
getCallingCodeFromNumber('invalid'); // => undefined (no fallback provided)
// Compare two numbers
isSameNumber('+12125551234', '(212) 555-1234', 'US'); // => true
// Validate for specific country
isValidForCountry('2125551234', 'US'); // => true
// RFC3966 format
formatRFC3966('2125551234', 'US'); // => 'tel:+1-212-555-1234'
formatRFC3966('invalid', undefined, 'N/A'); // => 'N/A' (returns fallback)
// Custom format
format('2125551234', 'E.164', 'US'); // => '+12125551234'
format('2125551234', 'INTERNATIONAL', 'US'); // => '+1 212 555 1234'
format('invalid', 'E.164', undefined, 'N/A'); // => 'N/A' (returns fallback)
支助国
电话模块支持所有国家 libphonenumber-js启用 getAvailableCountries() 以获取完整支持的国家代码列表.
最佳做法
何时提供 countryCode 参数 :
- ✅ 总是提供 在使用国家数字(例如,
'2125551234'(中文(简体) ) - ✅ 可选 当数字包括国家代码前缀(例如,
'+12125551234'(中文(简体) ) - ✅ 建议 用于所有格式化和验证功能以确保准确性
示例
// ✅ Good: National number with country code
formatPhoneNumber('2125551234', 'US'); // => '+12125551234'
// ✅ Good: International format with prefix
formatPhoneNumber('+12125551234'); // => '+12125551234'
// ⚠️ May fail: National number without country code
formatPhoneNumber('2125551234'); // => undefined (ambiguous)
解决问题:验证工作在Staging但不是生产
如果电话验证在生产上的表现与在中转上的表现不同,请检查以下内容:
-
过
countryCode在两种环境中
国家编号(无+前缀)需要国家代码. 如果 prod 使用不同的配置或 API 并省略countryCode,验证会失败。 总是喜欢通过它:
validatePhoneNumber(phone, countryCode)。 。 。 . -
国家代码格式
使用ISO 3166-1 α-2(例如.'US', (中文(简体) ),'GB') (中文(简体) ). 库将小写(如:.'us'→'US') (中文(简体) ). 确保 prod 不发送不同的格式(例如数字或3-字母). -
投入正常化
库会修剪白空格,并将常见的Unicode数字规范为ASCII. 如果prod从另一个系统收到数字(例如有前导/后导空格或非ASCII位数),则在验证前进行常态化. 如果您仍然看到差异, 请登录精确phoneNumber财务报告和审定财务报表countryCode与中转相比. -
依赖性版本
确保装配和推进@foodhubglobal/phone(因此libphonenumber-js) (中文(简体) ). 锁文件与安装脚本应完全相同,这样制作就不会得到更古老的构建.
类型脚本支持
该模块与TypeScript完全打入. 所有功能包括综合类型定义和JSDoc评论以更好的IDE支持,包括详细的参数描述和倒置行为文件.
import type { CountryCode, NumberFormat, NumberType } from '@foodhubglobal/phone';
快速引用:导入方法
视环境而定,使用适当的导入方法:
| 环境 | 普通JS( 必需) | ES模块(进口) |
|---|---|---|
| 节点.js | ✅ require('@foodhubglobal/phone') | ✅ import from '@foodhubglobal/phone' |
| 反应.js | ✅ require('@foodhubglobal/phone') (ESM偏爱) | ✅ import from '@foodhubglobal/phone' |
| 原生反应 | ✅ require('@foodhubglobal/phone') (ESM偏爱) | ✅ import from '@foodhubglobal/phone' |
| 纯 Java 脚本 | ✅ require(...) | ✅ import from ... |
说明: 这些公用设施纯粹是JavaScript功能. 该套件没有回放或回放原生依赖性,因此可以在任何JavaScript环境中被使用. 在React.js和React Entertainment项目中,Metro等捆绑者和常见的React建立设置一般都支持共同JS(require)和ES模块(import; ES模块被推荐用于新代码,但CommonJS仍然在这些环境中充分运作.
IDE 特性 :
- 所有功能的自动补全
- 包含 JSDoc 注释的内置文档
- 参数和返回值类型检查
- 工具提示中的实例
API 参考
电话模块函数
| 函数 | 说明 | 参数 | 回返 |
|---|---|---|---|
formatPhoneNumber(phone, country?, fallback?) | E.164格式的格式 | phone字符串 :, country?国家代码, fallback?字符串 | string | undefined |
formatInternational(phone, country?, fallback?) | 国际格式 | phone字符串 :, country?国家代码, fallback?字符串 | string | undefined |
formatNational(phone, country?, fallback?) | 国家格式格式 | phone字符串 :, country?国家代码, fallback?字符串 | string | undefined |
validatePhoneNumber(phone, country?) | 验证电话号码 | phone字符串 :, country?国家代码 | boolean |
isPossibleNumber(phone, country?) | 检查数字是否可行 | phone字符串 :, country?国家代码 | boolean |
formatAsYouType(phone, country?) | 格式为用户类型 | phone字符串 :, country?国家代码 | string |
parsePhone(phone, country?) | 分析并获取详细信息 | phone字符串 :, country?国家代码 | object |
getCountryFromPhoneNumber(phone, fallback?) | 从编号提取国家 | phone:字符串(必须包括国家前缀), fallback?国家代码 | CountryCode | undefined |
getCallingCode(country, fallback?) | 获取国家密码 | country国家代码, fallback?字符串 | string | undefined |
getAvailableCountries() | 获得所有支持的国家 | 无 | CountryCode[] |
extractPhoneNumber(text, country?, fallback?) | 从文本中取出编号 | text字符串 :, country?国家代码, fallback?字符串 | string | undefined |
getNumberType(phone, country?) | 获取数字类型 | phone字符串 :, country?国家代码 | NumberType | undefined |
isMobileNumber(phone, country?) | 检查手机号码 | phone字符串 :, country?国家代码 | boolean |
isFixedLineNumber(phone, country?) | 检查固定行号 | phone字符串 :, country?国家代码 | boolean |
normalizePhoneNumber(phone, country?, fallback?) | 常态化为 E.164 | phone字符串 :, country?国家代码, fallback?字符串 | string | undefined |
formatIncomplete(phone, country?) | 格式不完整编号 | phone字符串 :, country?国家代码 | string |
getNationalNumber(phone, country?, fallback?) | 获取国家编号 | phone字符串 :, country?国家代码, fallback?字符串 | string | undefined |
getCallingCodeFromNumber(phone, fallback?) | 从号码中调用代码 | phone:字符串(必须包括国家前缀), fallback?字符串 | string | undefined |
isSameNumber(phone1, phone2, country?) | 比较两个数字 | phone1字符串 :, phone2字符串 :, country?国家代码 | boolean |
isValidForCountry(phone, country) | 国家验证 | phone字符串 :, country国家代码 | boolean |
formatRFC3966(phone, country?, fallback?) | RFC3966的格式 | phone字符串 :, country?国家代码, fallback?字符串 | string | undefined |
format(phone, formatType, country?, fallback?) | 带有自定义格式的格式 | phone字符串 :, formatType: 数字格式, country?国家代码, fallback?字符串 | string | undefined |
说明:
- 这个
country?参数是可选的,但 高度建议 (没有国家代码前缀)。 省去国家编号时,函数可能返回undefined或由于模糊而出错的对象。 对于带有国家代码前缀的数字(例如,+1...),参数是可选的,国家是自动检测的. - 这个
fallback?参数是可选的,并提供错误处理:- 格式函数 (单位:千美元)
formatPhoneNumber, (中文(简体) ),formatInternational, (中文(简体) ),formatNational, (中文(简体) ),formatRFC3966, (中文(简体) ),format, (中文(简体) ),normalizePhoneNumber: 如果解析失败fallback提供,返回fallback; 否则返回原始内容phoneNumber。 。 。 . - 提取/获取函数 (单位:千美元)
extractPhoneNumber, (中文(简体) ),getNationalNumber, (中文(简体) ),getCallingCodeFromNumber, (中文(简体) ),getCountryFromPhoneNumber, (中文(简体) ),getCallingCode: 如果解析失败fallback提供,返回fallback; 否则返回undefined。 。 。 . - 解析函数 (单位:千美元)
parsePhone: 以isValid: false, isPossible: false当解析失败( 从未返回)null) (中文(简体) ).
- 格式函数 (单位:千美元)
捐款
许可证
版权所有 (c)2025-2026 Foodhub. 版权所有.
这个包裹是特许的,没有出售. 你可以安装它,并把它当作一个 依赖您自己的应用程序。 不可修改, 重新分配 单独设计,或逆向设计 见 自由主义 页:1 整个条件.
制造的 创建- 反应- 本土- 图书馆