文本框僅允許輸入數字(0-9)和小數點(.),其他字符(字母、符號、中文等)在輸入、粘貼、拖拽等所有途徑均被攔截。
var s = '<input type="text" size="20" ' +
'style="text-align:center" ' +
'onkeydown="if(event.keyCode>57&&event.keyCode!=190) return false" ' + // 鍵盤攔截
'onblur="value=value.replace(/[^0-9.]/g,\'\')" ' + // 失焦清洗
'onbeforepaste="clipboardData.setData(\'text\',clipboardData.getData(\'text\').replace(/[^0-9.]/g,\'\'))">'; // 粘貼過濾
document.write(s);
keyCode > 57 過濾非數字鍵(48-57),190 為小數點鍵碼。缺陷:小鍵盤數字碼不同、組合鍵(Ctrl+V)、輸入法輸入、中文輸入法下鍵碼干擾均可繞過。value.replace(/[^0-9.]/g, '') 移除所有非數字/小數點字符。兜底修正,但用戶輸入過程仍能看到非法字符。input.addEventListener('input', e => {
e.target.value = e.target.value.replace(/[^0-9.]/g, '');
// 可選:限制小數點個數
if ((e.target.value.match(/\./g) || []).length > 1) {
e.target.value = e.target.value.slice(0, -1);
}
});
優勢:覆蓋鍵盤、粘貼、拖拽、自動填充、輸入法確認等所有輸入途徑,瀏覽器原生支持,無兼容性問題。
<input type="number" step="0.01" min="0" />
瀏覽器原生數字輸入控件,帶步進器、驗證、移動端數字鍵盤。但樣式難定制、跨瀏覽器行為差異大。
form.addEventListener('submit', e => {
const val = input.value;
if (!/^\d+(\.\d+)?$/.test(val)) {
e.preventDefault();
alert('請輸入有效數字');
}
});
前端攔截不可靠,**後端驗證才是最後防線**。
class NumericInput {
constructor(selector, {decimals = 2, min = 0, max = Infinity} = {}) {
this.el = document.querySelector(selector);
this.decimals = decimals;
this.min = min;
this.max = max;
this.bind();
}
bind() {
this.el.addEventListener('input', () => this.filter());
this.el.addEventListener('blur', () => this.normalize());
}
filter() {
let v = this.el.value.replace(/[^0-9.]/g, '');
const dots = v.split('.');
if (dots.length > 2) v = dots[0] + '.' + dots.slice(1).join('');
if (this.decimals > 0 && dots[1] && dots[1].length > this.decimals) {
v = dots[0] + '.' + dots[1].slice(0, this.decimals);
}
this.el.value = v;
}
normalize() {
const v = parseFloat(this.el.value);
if (isNaN(v)) this.el.value = '';
else this.el.value = Math.min(Math.max(v, this.min), this.max).toFixed(this.decimals).replace(/\.?0+$/, '');
}
}
new NumericInput('#price', {decimals: 2, min: 0, max: 10000});