首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

jQuery 限制輸入框禁止非法字符輸入(正則驗證實戰)

     編輯:程式設計綜合問答

需求描述

使用 jQuery 控制輸入框,禁止用戶鍵盤輸入非法字符:`' " < > @ $ & % \`。

核心思路:鍵盤事件攔截 + 正則判斷

  1. 監聽 `keydown` / `keypress` / `input` 事件(推薦 `input` 事件,兼容中文輸入法、粘貼、拖拽)。
  2. 獲取當前輸入值或即將輸入的字符。
  3. 使用正則表達式測試是否包含非法字符。
  4. 若非法,阻止默認行為、移除非法字符、提示用戶。

推薦實現:`input` 事件 + 正則替換

// 定義非法字符正則(需轉義特殊元字符)
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 事件,然後利用正則表達式進行判斷。」—— 指出了事件與正則的關鍵組合。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved