使用 jQuery 控制輸入框,禁止用戶鍵盤輸入非法字符:`' " < > @ $ & % \`。
// 定義非法字符正則(需轉義特殊元字符)
const illegalRegex = /['"<>&$%\\]/g;
$('#txtInput').on('input', function(e) {
const $this = $(this);
const val = $this.val();
// 檢測並移除非法字符
if (illegalRegex.test(val)) {
const cleaned = val.replace(illegalRegex, '');
$this.val(cleaned);
// 可選:顯示提示
showTooltip($this, '輸入包含非法字符,已自動移除');
}
});
// 兼容舊版瀏覽器的 keypress 方案(僅攔截鍵盤輸入,不處理粘貼)
$('#txtInput').on('keypress', function(e) {
const char = String.fromCharCode(e.which);
if (illegalRegex.test(char)) {
e.preventDefault(); // 組織字符輸入
showTooltip($(this), `字符 "${char}" 不允許輸入`);
}
});
/['"<>&$%\\]/g
// 字符集 [...] 匹配任意單個字符
// ' " < > @ $ % \ 逐個列出
// \ 需雙重轉義:正則中 \ 是轉義,字符串中 \ 也是轉義 → \\\\
// g 全局標誌,替換所有匹配
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>輸入框非法字符攔截演示</title>
<style>
.invalid-tooltip { position:absolute; background:#ff4444; color:white; padding:4px 8px; border-radius:4px; font-size:12px; z-index:999; }
</style>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
</head>
<body>
<input type="text" id="txtInput" placeholder="嘗試輸入 ' \" < > @ $ % \" /" style="width:300px;padding:8px;font-size:16px;">
<script>
const illegalRegex = /['"<>&$%\\]/g;
let tooltipTimer;
function showTooltip($el, msg) {
$('.invalid-tooltip').remove();
const $tip = $('').text(msg);
$('body').append($tip);
const offset = $el.offset();
$tip.css({ top: offset.top - 30, left: offset.left });
clearTimeout(tooltipTimer);
tooltipTimer = setTimeout(() => $tip.fadeOut(300, () => $tip.remove()), 2000);
}
$('#txtInput').on('input', function() {
const $this = $(this);
if (illegalRegex.test($this.val())) {
$this.val($this.val().replace(illegalRegex, ''));
showTooltip($this, '已自動移除非法字符');
}
});
</script>
</body>
</html>
最佳實踐總結
- **雙重防護**:前端攔截提升體驗,**後端必須再次驗證**,防止繞過前端。
- **事件選擇**:`input` 事件覆蓋鍵盤、粘貼、拖拽、自動填充,最全面。
- **用戶體驗**:自動清理優於直接阻擋,避免「鍵盤失靈」困惑;配合 Toast 提示原因。
- **正則維護**:將非法字符集合提取為配置常量,便於業務調整。
最佳回答核心:「注冊 onkepup 事件,然後利用正則表達式進行判斷。」—— 指出了事件與正則的關鍵組合。
- 上一篇文章: WinForms TextBox 唯讀狀態動態切換實現
- 下一篇文章: Java 繼承中父類引用子類對象調用被覆蓋方法的行為分析