1。3-9(已覆蓋所有運營商:移動、聯通、電信、廣電、虛擬運營商)。0-9(無限制)。最簡通用正則:/^1[3-9]\d{9}$/
// 僅驗證格式,不限制具體號段(推薦,號段頻繁變動)
const MOBILE_REGEX = /^1[3-9]\d{9}$/;
// 如需嚴格號段(需定期更新),示例:
const STRICT_MOBILE = /^(?:13[\d]|14[5-9]|15[0-35-9]|16[2567]|17[0-8]|18[\d]|19[0-35-9])\d{8}$/;
// 13x, 145-149, 150-153/155-159, 162/165-167, 170-178, 18x, 190-193/195-199
// 格式:區號(3-4位)-號碼(7-8位)-分機(1-4位,可選)
// 區號可帶 0,也可不帶
const LANDLINE_REGEX = /^(?:0\d{2,3}-?)?\d{7,8}(?:-\d{1,4})?$/;
// 匹配示例:
// 010-12345678
// 021-87654321-123
// 12345678 (無區號)
/**
* 驗證手機/固話,自動識別類型
* @param {string} val - 輸入字符串
* @returns {{valid: boolean, type: 'mobile'|'landline'|'unknown', message: string}}
*/
function validatePhone(val) {
if (!val || typeof val !== 'string') return { valid: false, type: 'unknown', message: '輸入不能為空' };
const v = val.trim().replace(/[\s\-()()]/g, ''); // 移除常見分隔符
if (/^1[3-9]\d{9}$/.test(v)) {
return { valid: true, type: 'mobile', message: '' };
}
if (/^(?:0\d{2,3})?\d{7,8}(?:\d{1,4})?$/.test(v)) {
return { valid: true, type: 'landline', message: '' };
}
return { valid: false, type: 'unknown', message: '格式不正確:手機號 11 位數字,座機含區號 7-8 位數字' };
}
// 使用
const r = validatePhone(' 138-0013-8000 ');
if (r.valid) console.log('手機號:', r.type);
else alert(r.message);
<form id="contactForm">
<input type="tel" id="phone" name="phone" placeholder="手機/座機" required
pattern="^(?:1[3-9]\d{9}|(?:0\d{2,3}-?)?\d{7,8}(?:-\d{1,4})?)$"
title="請輸入正確的手機號或座機號">
<span class="error-msg" aria-live="polite"></span>
<button type="submit">提交</button>
</form>
<script>
document.getElementById('contactForm').addEventListener('submit', e => {
const input = document.getElementById('phone');
const r = validatePhone(input.value);
if (!r.valid) {
e.preventDefault();
input.setCustomValidity(r.message);
input.reportValidity();
document.querySelector('.error-msg').textContent = r.message;
} else {
input.setCustomValidity('');
}
});
</script>
若需支持國際號碼,強烈建議引入 libphonenumber-js(Google 官方庫),自動解析、驗證、格式化全球號碼。
import { parsePhoneNumberFromString } from 'libphonenumber-js';
const phone = parsePhoneNumberFromString('+86 138 0013 8000', 'CN');
if (phone && phone.isValid()) console.log(phone.formatInternational()); // +86 138 0013 8000
13[0-9]、15[89]),運營商新號段頻繁釋放,維護成本極高。+8613800138000)。type="tel" 可喚起移動端數字鍵盤。