簡體   English   中英

html中的電話字段驗證,允許數字和文本,但不允許@

[英]Tel field validation in html to allow digits and text but not @

該代碼僅允許使用數字-優先選擇允許輸入破折號和/或方括號,例如ext等文本。 但不是電子郵件地址。

您能幫我編輯此代碼嗎? 非常感激。

  <input type="text" maxlength="40" onkeypress="return event.charCode >= 48 && event.charCode <= 57" required name="phone" id="phonecontactselection">

您需要一個僅檢查@字符的函數來避免它,因此:

function avoidEmailPartCharacter(event) {
  const code = event.keyCode || event.which;
  if (code === 64) {
    event.preventDefault();
  }
}

然后將函數傳遞給輸入keypress處理程序,如下所示:

<input type="type" keypress={avoidEmailPartCharacter(this)} />

它應該可以解決問題

最好將這種out模板邏輯移到專用函數中,但是, 如果確實需要使其內聯 ,則可以按如下所示將輸入字符與正則表達式進行匹配:

 <input type="text" maxLength="40" onkeypress="return !!String.fromCharCode(event.which || event.charCode).match(/[\\dext\\[\\]\\-]/)" required name="phone" id="phonecontactselection" > 

您可以使用test和一個字符類,並列出允許匹配的字符。

在這種情況下,請匹配[] ,字符az ,點或連字符之一:

[\][a-z.-]

 <input type="text" maxlength="40" onkeypress="return /[\\][az.-]/.test(String.fromCharCode(event.which || event.keyCode));" required name="phone" id="phonecontactselection" > 

暫無
暫無

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

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