常用正則表達式
| 類型 | 正則 | 匹配示例 |
| 中國大陸手機號 | /^1[3-9]\d{9}$/ | 13812345678、15987654321 |
| 固定電話(含區號) | /^(0\d{2,3}-)?\d{7,8}(-\d{3,})?$/ | 021-87654321、0755-12345678-123 |
| 400/800 電話 | /^400[-\s]?\d{3}[-\s]?\d{4}$/ | 400-123-4567 |
| 通用電話(手機+固話) | /^(1[3-9]\d{9}|(0\d{2,3}-)?\d{7,8}(-\d{3,})?)$/ | 兼容以上所有 |
完整驗證函數
/**
* 驗證電話號碼格式
* @param {String} value - 待驗證字符串
* @returns {Object} { valid: Boolean, type: 'mobile'|'landline'|'400'|null, message: String }
*/
function validatePhone(value) {
if (!value || typeof value !== 'string') {
return { valid: false, type: null, message: '請輸入電話號碼' };
}
const trimmed = value.trim().replace(/\s+/g, ''); // 去除空格
const patterns = {
mobile: /^1[3-9]\d{9}$/,
landline: /^(0\d{2,3}-)?\d{7,8}(-\d{3,})?$/,
tollfree: /^400[-\s]?\d{3}[-\s]?\d{4}$/
};
if (patterns.mobile.test(trimmed)) {
return { valid: true, type: 'mobile', message: '' };
}
if (patterns.landline.test(trimmed)) {
return { valid: true, type: 'landline', message: '' };
}
if (patterns.tollfree.test(trimmed)) {
return { valid: true, type: '400', message: '' };
}
return {
valid: false,
type: null,
message: '格式錯誤,例:13812345678 或 021-87654321'
};
}
jQuery 表單驗證整合
$('#phoneForm').on('submit', function(e) {
const $input = $('#phoneInput');
const result = validatePhone($input.val());
if (!result.valid) {
e.preventDefault();
showError($input, result.message);
return false;
}
// 可選:格式化存儲
$input.val(formatPhone($input.val()));
});
function showError($el, msg) {
$el.addClass('error').next('.error-msg').remove();
$el.after(`${msg}`);
$el.one('input', () => $el.removeClass('error').next('.error-msg').remove());
}
號碼格式化(存儲/顯示統一)
function formatPhone(phone) {
const cleaned = phone.replace(/\D/g, '');
if (/^1[3-9]\d{9}$/.test(cleaned)) return cleaned; // 手機不加分隔
if (/^0\d{2,3}\d{7,8}$/.test(cleaned)) {
const area = cleaned.slice(0, cleaned.length === 11 ? 3 : 4);
const num = cleaned.slice(area.length);
return `${area}-${num}`;
}
return phone; // 其他保持原樣
}
注意事項
- 號段規則隨運營商政策變化,建議定期更新正則(如新增 16、17、19 段)
- 嚴格業務場景建議後端再次驗證,前端僅作首道攔截
- 國際號碼驗證極其複雜,推薦使用
libphonenumber 庫