javascriptformsvalidationonkeypress

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


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>

Solution

  • 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