在 Web 開發中,手機號碼驗證是表單校驗的核心環節之一。中國大陸的手機號段分配較為複雜,且隨著運營商不斷推出新號段,單純使用簡單正則(如 /^1\d{10}$/)已無法滿足業務需求。本文將系統講解如何結合正則表達式精準校驗國內手機號碼,並識別其所屬運營商(移動、聯通、電信及虛擬運營商),附帶可直接用於生產環境的工具函數封裝。
根據工信部最新號段分配標準(截至 2023 年),各運營商號段正則如下:
var isChinaMobile = /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/;
134[0-8]:1340-1348 專屬號段13[5-9]:135-139147:物聯網/數據卡專用15[0-27-9]:150-152、157-159178:4G 新號段18[2-478]:182-184、187-188var isChinaUnion = /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/;
13[0-2]:130-132145:物聯網專用15[56]:155-156176:4G 新號段18[56]:185-186var isChinaTelcom = /^(?:133|153|177|18[019])\d{8}$/;
133:早期 CDMA 號段153:3G 專用177:4G 新號段18[019]:180、181、189var isOtherTelphone = /^170[059]\d{7}$/;
虛擬運營商號段較多且變動快,建議業務層面僅做基礎格式校驗,具體歸屬可對接號碼歸屬地查詢 API。
將上述正則整合至統一工具對象,返回結構化結果:
var utils = {
// 去除首尾空白
trim: function(str) {
return str.replace(/^\s+|\s+$/g, '');
},
// 統一返回格式
setReturnJson: function(status, msg, data) {
if (typeof status !== 'boolean' && typeof status !== 'number') status = false;
if (typeof msg !== 'string') msg = '';
return { status: status, msg: msg, data: data };
},
// 核心校驗方法
checkMobile: function(telphone) {
telphone = this.trim(telphone);
// 長度預檢
if (telphone.length !== 11) {
return this.setReturnJson(false, '手機號碼長度應為 11 位');
}
// 依次匹配運營商
if (isChinaMobile.test(telphone)) {
return this.setReturnJson(true, '中國移動', { name: 'ChinaMobile' });
} else if (isChinaUnion.test(telphone)) {
return this.setReturnJson(true, '中國聯通', { name: 'ChinaUnion' });
} else if (isChinaTelcom.test(telphone)) {
return this.setReturnJson(true, '中國電信', { name: 'ChinaTelcom' });
} else if (isOtherTelphone.test(telphone)) {
return this.setReturnJson(true, '虛擬運營商', { name: 'VirtualOperator' });
} else {
return this.setReturnJson(false, '非有效的中國大陸手機號碼');
}
}
};
// 基本調用
var result = utils.checkMobile('13800138000');
console.log(result);
// { status: true, msg: '中國移動', data: { name: 'ChinaMobile' } }
// 表單驗證場景
$('#phoneInput').on('blur', function() {
var val = $(this).val();
var res = utils.checkMobile(val);
if (!res.status) {
showError(res.msg);
} else {
showSuccess('運營商:' + res.msg);
}
});
若僅需校驗格式,可使用通用正則:
// jQuery 版
var myreg = /^(((13[0-9])|(15[0-9])|(18[0-9]))+\d{8})$/;
if (!myreg.test($('#phone').val())) {
alert('請輸入有效的手機號碼!');
return false;
}
// 原生 JS 版
function validatemobile(mobile) {
if (!mobile || mobile.length !== 11) {
alert('請輸入 11 位手機號碼!');
return false;
}
var myreg = /^(((13[0-9])|(15[0-9])|(18[0-9]))+\d{8})$/;
if (!myreg.test(mobile)) {
alert('手機號碼格式不正確!');
return false;
}
return true;
}
libphonenumber 等專業庫處理各國號碼格式。通過精細化的正則表達式與工具函數封裝,可實現對中國大陸手機號碼的高精度校驗與運營商識別。實際項目中建議結合後端號碼歸屬地查詢服務,進一步提升準確率。完整代碼已整理為可直接引入的模塊,歡迎根據業務場景靈活調整。