For example, if I have a form and I don't want the user to enter numbers in it and I validate it with a function containing a regular expression, how do I prevent the invalid character the user entered (in this example, a digit) from showing up in the text form if it fails the regular expression test?

This is the function I tried and the select list I tried it on (in other words, this isn't the whole program). I tried returning false to the onkeypress event handler but what the user enters into the textbox still goes through.

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>
有帮助吗?

解决方案 2

This is the function you are looking for

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, '');
}

just send the input field reference to the function and set it to onkeyup event instead:

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

you should also hook the onchange event of the selectbox to reset the value of the input box. I suggest you also consider the HTML5 pattern attribute. See

其他提示

This validation works great for stripping invalid characters on the fly as you enter them in the relevant field. Example:

<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>

Then you would simply change the second value of the javascript call to the type of data you want entered in the field using the variables that are defined within the code.

You get the key being pressed from the event object passed to the handler.

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;
    }
  }
}

Googling for "onkeypress event" finds many examples of this.

Make your life simpler by adding an extra parameter to your validateAnswer function like this:
<input type="text" id="answer" name="answer" onkeyup="validateAnswer(this);" />

Then you can define your validateAnswer like this:

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

Here an example: http://jsbin.com/iwiduq/1/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top