實現表單驗證:手機號格式正確 + 統計數量 > 0 → 激活提交按鈕,否則按鈕置灰禁用。
// 運營商精確匹配 (2023年最新號段)
const regexMap = {
mobile: /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/, // 移動
unicom: /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/, // 聯通
telecom: /^(?:133|153|177|18[019])\d{8}$/, // 電信
others: /^170[059]\d{7}$/ // 虛擬運營商
};
// 通用驗證 (僅檢查格式)
const generalMobile = /^1[3-9]\d{9}$/;
const PhoneValidator = {
// 驗證手機號並返回運營商信息
checkMobile(telphone) {
telphone = this.trim(telphone);
if (telphone.length !== 11) {
return this.result(false, '手機號碼長度不正確');
}
for (const [carrier, regex] of Object.entries(this.regexMap)) {
if (regex.test(telphone)) {
return this.result(true, carrier, { carrier });
}
}
return this.result(false, '非有效手機號碼段');
},
trim(str) { return str.replace(/^\s+|\s+$/g, ''); },
result(status, msg, data = {}) {
return { status: !!status, msg: msg || '', data };
},
regexMap: {
mobile: /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/,
unicom: /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/,
telecom: /^(?:133|153|177|18[019])\d{8}$/,
others: /^170[059]\d{7}$/
}
};
// HTML
// JavaScript (jQuery)
$('#phone, #count').on('input', function() {
const phone = $('#phone').val();
const count = parseInt($('#count').val()) || 0;
const phoneValid = PhoneValidator.checkMobile(phone).status;
const countValid = count > 0;
$('#submitBtn').prop('disabled', !(phoneValid && countValid));
});
function validateForm() {
const phone = document.getElementById('phone').value;
const count = parseInt(document.getElementById('count').value) || 0;
const btn = document.getElementById('submitBtn');
// 簡單版驗證
const phoneRegex = /^1[3-9]\d{9}$/;
const isValid = phoneRegex.test(phone) && count > 0;
btn.disabled = !isValid;
btn.style.opacity = isValid ? '1' : '0.5';
btn.style.cursor = isValid ? 'pointer' : 'not-allowed';
}
// 綁定事件
document.getElementById('phone').addEventListener('input', validateForm);
document.getElementById('count').addEventListener('input', validateForm);
| 優化點 | 實現方式 | 收益 |
|---|---|---|
| 防抖處理 | input 事件 300ms 防抖 | 減少頻繁驗證開銷 |
| 視覺反饋 | 輸入框邊框顏色/圖標提示 | 提升用戶體驗 |
| 異步驗證 | 手機號唯一性後端校驗 | 業務邏輯完整性 |
| 無障礙支持 | aria-invalid / aria-describedby | 符合無障礙標準 |