萬盛學電腦網

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

輸入框限制只能輸入漢字(中文字符)的實現方案

核心正則

中文基本區:U+4E00 ~ U+9FA5(CJK Unified Ideographs)。

<input 
  onkeyup="this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '')" 
  onbeforepaste="clipboardData.setData('text', clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g, ''))"
/>

現代最佳實踐

<input id="chineseOnly" type="text" placeholder="僅限中文" />

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

input.addEventListener('input', function() {
  // 保留中文,移除其他
  this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '');
});

input.addEventListener('paste', function(e) {
  e.preventDefault();
  const text = (e.clipboardData || window.clipboardData).getData('text');
  const filtered = text.replace(/[^\u4E00-\u9FA5]/g, '');
  // 插入過濾後文本
  const start = this.selectionStart;
  const end = this.selectionEnd;
  this.value = this.value.slice(0, start) + filtered + this.value.slice(end);
  this.selectionStart = this.selectionEnd = start + filtered.length;
});
</script>

進階:支援擴展中文區塊

若需包含 CJK 擴展 A/B、兼容表意文字、中文標點:

// 擴展範圍(按需組合)
const EXTENDED_CJK = `
  \u3000-\u303F   // CJK 符號和標點
  \u3400-\u4DBF   // CJK 擴展 A
  \u4E00-\u9FFF   // CJK 基本區
  \uF900-\uFAFF   // CJK 兼容表意文字
  \u20000-\u2A6DF // CJK 擴展 B (需 ES2015+ u 標誌)
`;
// 使用時:new RegExp(`[^${EXTENDED_CJK.replace(/\s+/g, '')}]`, 'gu')

表單驗證輔助

function validateChineseOnly(value) {
  return /^[\u4E00-\u9FA5]+$/.test(value);
}
// 提交前調用
if (!validateChineseOnly(form.name.value)) {
  alert('姓名只能包含中文字符');
  return false;
}
copyright © 萬盛學電腦網 all rights reserved