/**
* 僅允許整數
* @param {string} selector - jQuery 選擇器,如 '#amount'
*/
function onlyInteger(selector) {
$(selector).on('keydown', function(e) {
const key = e.which || e.keyCode;
// 允許:Backspace(8), Delete(46), Tab(9), Esc(27), Enter(13),
// 左右鍵(37,39), Home(36), End(35), 數字鍵盤(96-105), 主鍵盤數字(48-57)
const allowed = [8, 9, 13, 27, 35, 36, 37, 39, 46];
const isNumberPad = key >= 96 && key <= 105;
const isMainNum = key >= 48 && key <= 57;
if (allowed.includes(key) || isNumberPad || isMainNum) return true;
e.preventDefault();
}).on('paste', function(e) {
// 阻止貼上非數字
const text = (e.originalEvent || e).clipboardData.getData('text');
if (!/^\d+$/.test(text)) e.preventDefault();
}).css('ime-mode', 'disabled'); // 關閉輸入法(舊 IE/Edge 有效)
}
/**
* 允許數字與單一小數點
*/
function onlyNumberWithDecimal(selector) {
$(selector).on('keydown', function(e) {
const key = e.which || e.keyCode;
const val = this.value;
const allowed = [8, 9, 13, 27, 35, 36, 37, 39, 46];
const isNumberPad = key >= 96 && key <= 105;
const isMainNum = key >= 48 && key <= 57;
const isDecimal = key === 190 || key === 110; // 主鍵盤 . / 數字鍵盤 .
if (allowed.includes(key) || isNumberPad || isMainNum) return true;
if (isDecimal) {
// 已有小數點 或 游標在開頭 禁止
if (val.includes('.') || this.selectionStart === 0) {
e.preventDefault();
}
return true;
}
e.preventDefault();
}).on('input', function() {
// 雙重保障:貼上、拖曳、IME 輸入後二次過濾
this.value = this.value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
}).css('ime-mode', 'disabled');
}
// 使用範例
$(function() {
onlyInteger('#intInput');
onlyNumberWithDecimal('#floatInput');
});
<!-- 僅整數,瀏覽器原生驗證 -->
<input type="number" id="nativeInt" step="1" min="0" placeholder="僅整數">
<!-- 允許小數,step="any" 或 step="0.01" -->
<input type="number" id="nativeFloat" step="0.01" min="0" placeholder="可輸入小數">
<script>
// 補強:阻止 e 鍵(科學記號)與上下鍵修改值
document.querySelectorAll('input[type="number"]').forEach(el => {
el.addEventListener('keydown', e => {
if (['e','E','ArrowUp','ArrowDown'].includes(e.key)) e.preventDefault();
});
el.addEventListener('wheel', e => e.preventDefault()); // 滾輪不改值
});
</script>
優點:原生 UI(含微調鈕)、行動裝置自動喚起數字鍵盤、無 JS 也能基本驗證。
缺點:樣式難客製化、舊瀏覽器支援度較低、無法完全禁用貼上非數字。
input 事件即時過濾(最簡單、相容性最好)<input type="text" id="simpleInt" oninput="this.value=this.value.replace(/\D/g,'')" placeholder="僅整數">
<input type="text" id="simpleFloat" oninput="this.value=this.value.replace(/[^\d.]/g,'').replace(/\.{2,}/g,'.').replace(/^\./,'')" placeholder="可輸入小數">
原理:每次輸入後立即用正則清理非法字元。缺點:游標位置會跳動、中文輸入法佇列字元可能閃爍。
function limitDecimals(selector, maxDecimals = 2) {
$(selector).on('input', function() {
let val = this.value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
if (val.includes('.')) {
const [intPart, decPart] = val.split('.');
if (decPart.length > maxDecimals) {
val = intPart + '.' + decPart.slice(0, maxDecimals);
}
}
this.value = val;
});
}
| 方案 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|
| jQuery 事件綁定 | 既有 jQuery 專案、需精細控制鍵盤行為 | 可控制游標、支援貼上過濾、可複用 | 需引入 jQuery |
| HTML5 type="number" | 新專案、行動裝置優先、不需複雜客製 | 零 JS、原生鍵盤、語意化 | 樣式受限、舊瀏覽器不支援 |
| oninput 正則清理 | 快速原型、相容極舊環境 | 一行搞定、無依賴 | 游標跳動、體驗較差 |