I'm attempting to do info validation against user text input in the process of keydown
event. The reason that I am trying to validate in the keydown
event is because I do not want to display the characters those that are considered to be illegal in the input
box at the beginning.
The validation I am writing is like this,
function validateUserInput(){
var code = this.event.keyCode;
if ((code<48||code>57) // numerical
&&code!==46 //delete
&&code!==8 //back space
&&code!==37 // <- arrow
&&code!==39) // -> arrow
{
this.event.preventDefault();
}
}
I can keep going like this, however I am seeing drawbacks on this implementation. Those are, for example:
keyCodes
can be different by browsers. But the feature that I don't want to lose is having not to display the input in the textarea
unless it passes the validation. (In case the user try to put illegal characters in the textarea
, nothing should appear at all) That is why I am not doing validation upon keyup
event.
So my question is:
keydown
event than checking keyCode
by keyCode
?keydown
event before browser displays it? And a way to put the validation on it?If you're checking a printable key, which is exactly what you seem to be doing, you should use the keypress
event instead, since that's the only place you're going to be able to get reliable information about the character the keypress represents. You can't detect numeric keypresses reliably in the keydown
event. Also, it's a bad idea to suppress arrow keys and delete/backspace keys. What do you gain from doing that?
There's also some errors: in Firefox, you'll need to get the Event
object from the parameter passed into the event handler function, and if you're using a DOM0 event handler function rather than addEventListener()
or attachEvent()
, you should use return false;
to suppress default behaviour. Here's my recommended code:
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (/\d/.test(charStr)) {
return false;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With