電話號碼格式驗證是表單檢核的高頻需求。本文分析常見正則模式的優缺點,指出單純字符檢查的不足,提供更嚴格、符合實際業務的驗證方案。
function isTel(str) {
var reg = /^([0-9]|[-])+$/g; // 僅允許數字與連字號
if (str.length < 7 || str.length > 18) return false;
return reg.exec(str);
}
--123-- 等無效格式exec() 返回陣列而非布林,直接用於 if 判斷雖可運作但語意不清function validatePhone(phone) {
if (!phone || typeof phone !== 'string') return false;
// 移除常見分隔符
const cleaned = phone.replace(/[\s\-()()]/g, '');
// 手機號:11位,1開頭,第二位3-9
const mobileRegex = /^1[3-9]\d{9}$/;
// 座機:區碼(3-4位) + 號碼(7-8位),可選分機
const landlineRegex = /^0\d{2,3}\d{7,8}(-\d{1,6})?$/;
// 400/800/95 開頭服務熱線
const serviceRegex = /^(400|800|95)\d{7,}$/;
return mobileRegex.test(cleaned)
|| landlineRegex.test(cleaned)
|| serviceRegex.test(cleaned);
}
// 國際標準格式:+[國家碼][號碼],如 +8613812345678
function validateInternationalPhone(phone) {
const e164Regex = /^\+[1-9]\d{1,14}$/; // ITU-T E.164 標準
return e164Regex.test(phone.replace(/[\s\-()()]/g, ''));
}
test() 而非 exec():語意明確、效能稍優input 事件中即時驗證、顯示格式提示| 地區 | 正則 | 例子 |
|---|---|---|
| 中國大陸 | ^1[3-9]\d{9}$ | 13812345678 |
| 台灣 | ^09\d{8}$ | 0912345678 |
| 香港 | ^[569]\d{7}$ | 91234567 |
| 美國/加拿大 | ^\+1[2-9]\d{9}$ | +14155551234 |
<form id="phoneForm">
<input type="tel" id="phone" placeholder="請輸入手機號碼" required />
<span class="error" id="phoneError"></span>
<button type="submit">提交</button>
</form>
<script>
document.getElementById('phoneForm').addEventListener('submit', function(e) {
e.preventDefault();
const phone = document.getElementById('phone').value.trim();
const errorEl = document.getElementById('phoneError');
if (validatePhone(phone)) {
errorEl.textContent = '';
alert('格式正確,發送驗證碼...');
// sendSMS(phone);
} else {
errorEl.textContent = '請輸入有效的手機或座機號碼';
}
});
document.getElementById('phone').addEventListener('input', function() {
const phone = this.value.replace(/[^\d]/g, '');
this.value = phone; // 只保留數字
});
電話驗證看似簡單,實則涉及業務分類、國際化、使用者體驗等多維考量。建立可維護的驗證函數庫,比寫一個「萬能正則」更務實。