限制 input 輸入框只能輸入xxx

限制 input 輸入框只能輸入xxx

  • 使用 onkeyup 事件,有 bug ,那就是在中文輸入法狀態下,輸入漢字之後直接回車,會直接輸入字母
  • 使用 onchange 事件,在輸入內容後,只有 input 喪失焦點時纔會得到結果,並不能在輸入時就做出響應
  • 使用 oninput 事件,完美的解決了以上兩種問題,測試暫時還沒有出現其它問題。

原理就是在輸入時會觸發事件,事件會通過字符替換和正則表達式將不符合規範的替換掉(刪除掉)

輸入大小寫字母、數字、下劃線:

<input type="text" oninput="value=this.value.replace(/[^\w_]/g,'');"> 

輸入小寫字母、數字、下劃線:

<input type="text" oninput="value=this.value.replace(/[^a-z0-9_]/g,'');"> 

輸入數字和點

<input type="text" oninput="value=value.replace(/[^\d.]/g,'')">

輸入中文:

<input type="text" oninput="value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')">  

輸入數字:

<input type="text" oninput="value=this.value.replace(/\D/g,'')">  

輸入英文:

<input type="text" oninput="value=this.value.replace(/[^a-zA-Z]/g,'')">  

輸入中文、數字、英文:

<input oninput="value=value.replace(/[^\w\u4E00-\u9FA5]/g, '')">  

輸入數字和字母:

<input oninput="value=value.replace(/[\W]/g,'')">  

只能輸入英文字母和數字,不能輸入中文

<input oninput="value=value.replace(/[^\w\.\/]/ig,'')">

只能輸入數字和英文

<input oninput="value=value.replace(/[^\d|chun]/g,'')">

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章