Skip to content
Advertisement

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.

JavaScript

Advertisement

Answer

This is the function you are looking for

JavaScript

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

JavaScript

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement