簡體   English   中英

HTML 文本輸入,使用 JS 正則表達式只允許輸入某些字符

[英]HTML text input, using JS regex to only allow certain characters to be typed

我對 Regex 並不太熟悉,我剛剛開始使用 Javascript。

我試圖做到這一點,當用戶在 textarea 中鍵入時,他們被迫遵循某種模式。 模式是“X”后跟 9 個數字。 如果第一個字符是除 'X' 以外的任何字母,則它不會鍵入,並且在他們鍵入 'X' 之后,如果它是數字以外的任何字符,則不會鍵入,或者如果它是一系列更長的數字超過 9 位數字,那么它也不會打字。

現在使用我得到的代碼,它會為第一個字符尋找一個字母,雖然不是專門的“X”,並且有點相反,因為它等待直到滿足這個模式,然后用任何東西替換文本.

<textarea id="scan-data" onkeypress="if(this.value.match(/^[A-Za-z][0-9]{9,9}$/gm)) this.value=this.value.replace(/^[A-Za-z][0-9]{9,9}$/gm,'')" onkeyup="if(this.value.match(/^[A-Za-z][0-9]{9,9}$/gm)) this.value=this.value.replace(/^[A-Za-z][0-9]{9,9}$/gm,'')"></textarea><br>

textarea 中允許的唯一文本應該是 X 和 9 位數字,其他任何內容都應該自動替換為“”(即沒有)

感謝任何人可以提供的任何幫助! 謝謝

x.value.replace(/^(X\d{0,9})?.*$\n?/gm, (x,y) => y !== undefined ? y + (y.length==10 ? '\n' : '') : '');

看看表達式是如何工作的

JavaScript 代碼

 function myFunction(x){ x.value = x.value.replace(/^(X\\d{0,9})?.*$\\n?/gm, (x,y) => y !== undefined ? y + (y.length==10 ? '\\n' : '') : ''); }
 <textarea id="scan-data" onkeyup="myFunction(this)"></textarea><br>

解釋

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to $1 (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    X                        'X'
--------------------------------------------------------------------------------
    \d{0,9}                  digits (0-9) (between 0 and 9 times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )?                       end of $1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in $1)
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        the end of the line
--------------------------------------------------------------------------------
  \n?                      an optional LF (line  feed) symbol

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM