萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 限制輸入框僅允許中文字符:多種實現方案與兼容性分析

核心需求

在表單輸入場景中(如中文姓名、地址、備註),強制限制用戶只能輸入中文字符(漢字),自動過濾字母、數字、符號、表情符等。

方案一:原生 oninput + 正則替換(推薦,現代瀏覽器)

<input type="text" id="chineseOnly" placeholder="請輸入中文">

<script>
const input = document.getElementById('chineseOnly');

// 核心邏輯:輸入時即時過濾
input.addEventListener('input', function() {
    // 保留基本多文種平面 (BMP) 中的中日韓統一表意文字
    // 範圍:\u4E00-\u9FA5 (常用漢字 20902 個)
    // 擴展:\u3400-\u4DBF (擴展區 A) | \u20000-\u2A6DF (擴展區 B) 等
    this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '');
});

// 處理粘貼
input.addEventListener('paste', function(e) {
    e.preventDefault();
    const text = (e.clipboardData || window.clipboardData).getData('text');
    this.value = text.replace(/[^\u4E00-\u9FA5]/g, '');
    // 觸發 input 事件讓綁定的驗證生效
    this.dispatchEvent(new Event('input', {bubbles: true}));
});
</script>

方案二:jQuery 版(兼容舊項目)

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#chineseOnly').on('input paste', function(e) {
    if (e.type === 'paste') {
        e.preventDefault();
        const text = e.originalEvent.clipboardData.getData('text');
        $(this).val(text.replace(/[^\u4E00-\u9FA5]/g, ''));
    } else {
        $(this).val(this.value.replace(/[^\u4E00-\u9FA5]/g, ''));
    }
});
</script>

方案三:HTML5 pattern 屬性(表單驗證層面)

<form>
    <input type="text" 
           pattern="[\u4E00-\u9FA5]+" 
           title="僅允許輸入中文字符"
           required>
    <button type="submit">提交</button>
</form>
<style>
    input:invalid { border-color: red; }
    input:valid { border-color: green; }
</style>

注意:pattern 僅在提交時驗證,不阻止輸入,需配合 JS 即時過濾。

方案四:CSS ime-mode(已棄用,僅 IE/Edge 旧版支持)

<style>
.chinese-only { ime-mode: active; } /* 強制開啟輸入法 */
</style>
<input class="chinese-only">

⚠️ 不推薦使用:已從標準移除,現代瀏覽器忽略此屬性。

正則表達式深度解析

正則覆蓋範圍字符數適用場景
[\u4E00-\u9FA5]CJK 統一表意文字 (基本區)20,902通用中文輸入(推薦)
[\u3400-\u4DBF]CJK 擴展區 A6,582人名、地名罕見字
[\u20000-\u2A6DF]CJK 擴展區 B (需 surrogate pair)42,711古漢字、專業術語
[\p{Script=Han}]所有漢字 (Unicode 13+ / ES2018+)90,000+現代環境,最全面

現代寫法:Unicode 屬性逃逸 (ES2018+)

// 需支持 ES2018+ (Chrome 64+, Firefox 78+, Safari 13+)
const HAN_REGEX = /[^\p{Script=Han}]/gu;

input.addEventListener('input', () => {
    input.value = input.value.replace(HAN_REGEX, '');
});

完整可用組件封裝

class ChineseInput {
    constructor(selector, options = {}) {
        this.el = typeof selector === 'string' ? document.querySelector(selector) : selector;
        this.options = Object.assign({
            allowDigits: false,      // 是否允許數字
            allowPunctuation: false, // 是否允許中文標點
            maxLength: 0             // 最大長度 0=不限
        }, options);
        this.init();
    }

    init() {
        this.el.addEventListener('input', this.handleInput.bind(this));
        this.el.addEventListener('paste', this.handlePaste.bind(this));
    }

    buildRegex() {
        let pattern = '\\u4E00-\\u9FA5';
        if (this.options.allowDigits) pattern += '0-9';
        if (this.options.allowPunctuation) pattern += '\\u3000-\\u303F'; // 中文標點區
        return new RegExp(`[^${pattern}]`, 'g');
    }

    handleInput() {
        this.el.value = this.el.value.replace(this.buildRegex(), '');
        if (this.options.maxLength && this.el.value.length > this.options.maxLength) {
            this.el.value = this.el.value.slice(0, this.options.maxLength);
        }
    }

    handlePaste(e) {
        e.preventDefault();
        const text = (e.clipboardData || window.clipboardData).getData('text');
        this.el.value = text.replace(this.buildRegex(), '');
        this.el.dispatchEvent(new Event('input', {bubbles: true}));
    }
}

// 使用
new ChineseInput('#nameInput', {maxLength: 20});
new ChineseInput('#addressInput', {allowPunctuation: true, maxLength: 100});

常見問題與避坑

  • 光標跳動:替換 value 會導致光標跳到末尾,解決:記錄 selectionStart/End 恢復
  • 組合輸入法:中文輸入法編碼過程中(composition)不應過濾,需監聽 compositionstart/end
  • 表情符號:Emoji 屬於補充平面,\u4E00-\u9FA5 自動過濾,但 \p{Script=Han} 更語義化
  • 無障礙性:配合 aria-describedby 提示輸入規則

總結

現代項目推薦 方案一(原生 input 事件 + 正則),配合 compositionstart/end 處理輸入法組合狀態。舊項目可用 jQuery 版。表單提交層面務必加服務端二次驗證,前端攔截只是體驗優化,非安全邊界。

copyright © 萬盛學電腦網 all rights reserved