表單驗證的第一道防線是在輸入時即攔截非法字元。本文彙整常見的「只能輸入 XX」正則與事件處理模式,涵蓋純數字、數字含小數、英數、中文、禁止特殊符號等場景,並說明現代最佳實踐。
| 需求 | 推薦寫法(oninput/onkeyup) | 說明 |
|---|---|---|
| 只能輸入整數(含負號) | oninput="value=value.replace(/[^-\d]/g,'')" | 允許開頭負號 |
| 只能輸入正整數 | oninput="value=value.replace(/\D/g,'')" | \D = 非數字 |
| 數字含小數點(最多兩位) | oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\-?\d+\.\d{2}).*$/,'$1')" | 先濾非數字/點,再限制小數位 |
| 只能輸入英文字母、數字、底線 | oninput="value=value.replace(/[^\w]/g,'')" | \w = [A-Za-z0-9_] |
| 只能輸入中文 | oninput="value=value.replace(/[^\u4e00-\u9fa5]/g,'')" | Unicode 範圍 |
| 中英數混合 | oninput="value=value.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g,'')" | 常用於姓名、地址 |
| 禁止空格 | oninput="value=value.replace(/\s/g,'')" | \s 含空白、Tab、換行 |
| 禁止特殊符號(!@#$%^&* 等) | oninput="value=value.replace(/[!@#$%^&*]/g,'')" | 依需求增減字元 |
<input type="text" placeholder="只能輸入數字" oninput="this.value=this.value.replace(/\D/g,'')">
<input type="text" placeholder="數字含小數(2位)" oninput="this.value=this.value.replace(/[^\d.]/g,'').replace(/^(\-?\d+\.\d{2}).*$/,'$1')">
<input type="text" placeholder="中英數" oninput="this.value=this.value.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g,'')">
<input type="text" placeholder="只能中文" oninput="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')">
<input type="text" placeholder="英數底線" oninput="this.value=this.value.replace(/[^\w]/g,'')">
<!-- 數字輸入,內建步進器、驗證 -->
<input type="number" step="0.01" min="0" max="100">
<!-- 信用卡、電話等特定格式 -->
<input type="text" pattern="\d{4}-\d{4}-\d{4}-\d{4}" title="格式:1234-5678-9012-3456">
<!-- 禁止輸入法(行動裝置) -->
<input type="text" inputmode="numeric"> <!-- 數字鍵盤 -->
<input type="text" inputmode="decimal"> <!-- 數字+小數點 -->
<input type="text" inputmode="text"> <!-- 全鍵盤 -->
搭配 required、minlength、maxlength 即可完成大部分驗證,無需 JS。
// Vue 3 指令 v-numeric
app.directive('numeric', {
mounted(el, binding) {
const { decimals = 0, min, max } = binding.value || {};
const regex = new RegExp(`[^\\d${decimals ? '.' : ''}-]`);
el.addEventListener('input', () => {
let v = el.value.replace(regex, '');
if (decimals) v = v.replace(new RegExp(`^(-?\\d+\\.\\d{${decimals}}).*$`), '$1');
if (min !== undefined && +v < min) v = min;
if (max !== undefined && +v > max) v = max;
el.value = v;
});
}
});
// 使用:
\d 匹配 Unicode 數字(含全形),嚴格 ASCII 請用 [0-9]。oninput 會觸發一次,效能較好;避免在 onkeypress 中做複雜運算。input 但值未確定,若需精確控制請監聽 compositionstart/end。