Input Validation In The Keydown Event
Solution 1:
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)) {
returnfalse;
}
};
Solution 2:
I don't think you need the preventDefault part. If you want to catch keys (by event.keyCode
, or combinations using for example event.ctrlKey
+ event.keyCode
), you check if the keyCode
is allowed. If it is, simply return true
, otherwise return false
. If you return false
, the key input will not be written to the input field, otherwise it will.
I can't think of better ways to then using keyCode. You can use String.fromCharCode([keyCode])
if you want to check for specific character values, but it keeps boiling down to some loop to check the keyCodes you want to validate. May be a switch ... case
could offer a bit more readability.
Here's a piece of code from a keydown event handler I use (just for demonstration, it doesn't actually do anything):
function handleKey(e, thisFld) {
thisFld = (thisFld || this);
e = e || event;
if (!e) {
returntrue;
}
var isCtrl = e.ctrlKey,
isShift = e.shiftKey,
isAlt = e.altKey,
kc = e.keyCode || e.which,
codes = [27, 38, 40],
keys = {
escape: 27,
up: 38,
down: 40,
ins: 45,
del: 46,
one: 49
};
if (isCtrl && kc === keys.del) { ... }
if (isAlt && kc === keys.ins) { ... }
//etcreturntrue;
}
Solution 3:
here's a fiddle that you can play with and may provide more insight.
jsfiddle: keydown/keypress demo w/ info display
It would appear that the latest browsers use preventDefault(). The code below is similar to what i put on jsfiddle but is standalone and can be pasted into an html file that you can access locally to test (note it's mobile friendly for device testing.
<html><head><metaname="viewport"content="initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, user-scalable=no"/><style>.b {color:blue;}
.r {color:red;}
input {font-size:18px;}
</style><script>functionbyId(el) {returndocument.getElementById(el)}
functionsfcc (n) {returnString.fromCharCode(n);}
functionfoo(event) {
var he='&#x'+event.keyIdentifier.split('+')[1]+';';
var html=''var cn=event.target.className;
html+='kc: [<span class="b">'+sfcc(event.keyCode)+'</span>] ';
html+='wh: [<span class="b">'+sfcc(event.which)+'</span>] ';
html+='he: [<span class="b">'+he+'</span>]<br>';
for (i in event)
if (["string","boolean","number"].indexOf(typeof event[i]) >-1 && i.toUpperCase()!=i)
html+='<span>'+i + '</span>: [<span class="r">'+event[i]+'</span>]<br>';
byId('kc').innerHTML=html;
switch (cn) {
case"pd": event.preventDefault(); return;
case"rf": returnfalse;
}
}
</script></head><body>
kp/pd: <inputclass="pd"type="text"onkeypress="foo(event)"/><br>
kp/rf: <inputclass="rf"type="text"onkeypress="foo(event)"/><br>
kd/pd: <inputclass="pd"type="text"onkeydown="foo(event)"/><br>
kd/rf: <inputclass="rf"type="text"onkeydown="foo(event)"/><br><divid="kc"></div></body></html>
Solution 4:
So, I've found that keypress is great for printable characters, and keydown for all the rest. You can check the event.charCode
on keypress
for printable characters (it should be 0 for non-printable).
You can use event.keyCode
on keydown
for arrows and such.
This is how I just got an autocomplete to work in Chrome and Firefox.
Post a Comment for "Input Validation In The Keydown Event"