如何防止将无效字符输入表单?

时间:2013-03-31 08:09:56

标签: javascript forms validation onkeypress

例如,如果我有一个表单,并且我不希望用户在其中输入数字并使用包含正则表达式的函数对其进行验证,那么如何防止用户输入的无效字符(在这个例子,如果一个数字在正则表达式测试中失败,它会以文本形式出现吗?

这是我尝试的功能和我尝试过的选择列表(换句话说,这不是整个程序)。我尝试将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>

4 个答案:

答案 0 :(得分:1)

当您在相关字段中输入无效字符时,此验证非常适合即时剥离无效字符。示例:

<form id="form1" name="form1" method="post">
  Email:
  <input type="text" name="email" id="email" onkeyup='res(this, emailaddr);' ; </form>

  <script>
    var phone = "()-+ 0123456789";
    var numb = "0123456789";
    var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ @-'.,";
    var alphanumb = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ @-.'1234567890!?,:;£$%&*()";
    var alphaname = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,-.1234567890";
    var emailaddr = "0123456789@._abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    function res(t, v) {
      var w = "";
      for (i = 0; i < t.value.length; i++) {
        x = t.value.charAt(i);
        if (v.indexOf(x, 0) != -1)
          w += x;
      }
      t.value = w;
    }
  </script>

然后,您只需使用代码中定义的变量将 javascript 调用的第二个值更改为您要在字段中输入的数据类型。

答案 1 :(得分:0)

通过在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/

答案 2 :(得分:0)

您从传递给处理程序的事件对象中获取了按键。

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事件”找到了很多这方面的例子。

答案 3 :(得分:0)

这是您正在寻找的功能

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。参见