手機號與固話驗證是表單校驗高頻需求。本文提供嚴格的正則表達式、字符串原型擴展方法、表單驗證完整流程,並分析正則維護難點與現代替代方案。
// 簡化版:13-19 開頭 11 位數字
/^1[3-9]\d{9}$/
// 精確版:按運營商號段(需定期更新)
/^(?:
13[0-9]| // 聯通/移動
14[0-9]| // 衛星/物聯網
15[0-35-9]| // 移動/聯通(除154)
16[267]| // 聯通
17[0-8]| // 虛擬運營商
18[0-9]| // 移動/聯通/電信
19[0-9] // 5G/新號段
)\d{8}$/
// 格式:[國家碼-]區號-號碼[-分機]
/^(?:\+?86[- ]?)?(?:0\d{2,3}[- ]?)?\d{7,8}(?:[- ]?\d{1,6})?$/
// 匹配示例:
// 0712-3614072
// 021-87888888
// +86-021-87888888
// 010-12345678-123
<script>
// 去除首尾空白
String.prototype.Trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
// 手機驗證
String.prototype.isMobile = function() {
return /^1[3-9]\d{9}$/.test(this.Trim());
};
// 固話驗證
String.prototype.isTel = function() {
return /^(?:\+?86[- ]?)?(?:0\d{2,3}[- ]?)?\d{7,8}(?:[- ]?\d{1,6})?$/.test(this.Trim());
};
// 表單驗證入口
function chkForm() {
var tel = document.form1.tel.value;
if (tel.isMobile() || tel.isTel()) {
alert('您的電話/手機號碼是:' + tel.Trim());
return true;
} else {
alert('請輸入正確的手機號碼或電話號碼\n例如:13916752109 或 0712-3614072');
document.form1.tel.focus();
return false;
}
}
</script>
<form name="form1">
<input type="text" name="tel" value="13916752109" size="15" />
<input type="button" value="測試" onclick="return chkForm()" />
</form>
npm install libphonenumber-js
import { parsePhoneNumberFromString } from 'libphonenumber-js';
function validatePhone(input, defaultCountry = 'CN') {
const phone = parsePhoneNumberFromString(input, defaultCountry);
return phone && phone.isValid();
}
// 使用
validatePhone('13916752109'); // true
validatePhone('0712-3614072', 'CN'); // true
validatePhone('+1 234 567 8900', 'US'); // true
// 獲取格式化號碼
const phone = parsePhoneNumberFromString('13916752109', 'CN');
phone.formatInternational(); // "+86 139 1675 2109"
phone.formatNational(); // "139 1675 2109"
phone.getType(); // "MOBILE" / "FIXED_LINE"
// config/mobile-prefixes.js (定期自動更新)
export const MOBILE_PREFIXES = [
'130','131','132','133','134','135','136','137','138','139',
'145','146','147','148','149',
'150','151','152','153','155','156','157','158','159',
'162','165','166','167',
'170','171','172','173','174','175','176','177','178',
'180','181','182','183','184','185','186','187','188','189',
'190','191','192','193','195','197','198','199'
];
// 驗證函數
function isMobile(phone) {
if (!/^1\d{10}$/.test(phone)) return false;
var prefix = phone.slice(0, 3);
return MOBILE_PREFIXES.includes(prefix);
}
input 事件防抖驗證,顯示綠勾/紅叉139 1675 2109 提升可讀性簡單項目用 /^1[3-9]\d{9}$/ 基礎正則;生產項目強烈推薦 libphonenumber-js 專業庫,自動維護全球號段、支援格式化、類型識別、國際化。切記:正則只能做格式校驗,不能替代驗證碼驗證真實性。