簡體   English   中英

如何防止將無效字符輸入表單?

[英]How do I prevent invalid characters from being entered into a form?

例如,如果我有一個表單,並且我不希望用戶在其中輸入數字,而是使用包含正則表達式的函數對其進行驗證,那么如何防止用戶輸入的無效字符(在本示例中為數字) )從文本表單中顯示(如果未通過正則表達式測試)?

這是我嘗試過的功能,也是我嘗試過的選擇列表(換句話說,這不是整個程序)。 我嘗試將false返回到onkeypress事件處理程序,但用戶在文本框中輸入的內容仍然可以通過。

function noNumbers(answer) {  //returns false and displays an alert if the answer contains numbers
     if (/[\d]+/.test(answer)) {    // if there are numbers
         window.alert("You can not enter numbers in this field");
         return false;
     }

}

<form action="get" enctype="application/x-www-form-urlencoded">
    <select id="questions" name="questions">
         <option value="no_numbers">What is the name of the city where you were born?</option>
         <option value="no_letters">What is your phone number?</option>
         <option value="no_numbers">What is the name of your favorite pet?</option>
         <option value="no_letters">What is your social security number?</option>
         <option value="no_numbers">What is your mother's maiden name?</option>  
    </select>
    <p><input type="text" name="answer" onkeypress="validateAnswer();" /></p>
</form>

通過在validateAnswer函數中添加一個額外的參數,使生活更簡單,如下所示:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />

然后,您可以定義您的validateAnswer如下所示:

function validateAnswer(elem){
    elem.value = elem.value.replace(/[^\d]/g, '');
}

下面是一個示例: http : //jsbin.com/iwiduq/1/

您可以從傳遞給處理程序的事件對象中獲得按下的鍵。

input type="text" name="answer" onkeypress="validateAnswer(this, event);" />

function validateAnswer(element, event) {
  if (event.charCode) {
    if (/\d/.test(String.fromCharCode(event.charCode))) {
      window.alert("You can not enter numbers in this field");
      return false;
    }
  }
}

谷歌搜索“ onkeypress事件”可以找到許多示例。

這是您要尋找的功能

function validateAnswer(src) {
    var questions = document.getElementById("questions");
    var rule = questions.options[questions.selectedIndex].value;
    if(rule=="no_numbers") src.value = src.value.replace(/\d/g, '');
    if(rule=="no_letters") src.value = src.value.replace(/\w/g, '');
}

只需將輸入字段引用發送給函數並將其設置為onkeyup事件即可:

<input type="text" name="answer" onkeyup="validateAnswer(this);" />

您還應該掛鈎選擇框的onchange事件以重置輸入框的值。 我建議您也考慮HTML5 pattern attribute 看到

暫無
暫無

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

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