The issue:
Take a look at your third condition:
keycode < 96 || keycode > 105 //Where keycode is NOT between 96-105
Now look at the ASCII codes for the characters you entered:
a: 97
b: 98
c: 99
d: 100
e: 101
f: 102
g: 103
h: 104
It should now be obvious why your code is failing - You've included a condition that very specifically ignores the characters you're claiming "don't work".
keyCode vs charCode:
When it comes to keyCode
, you're going to run into some cross-browser issues. For that reason you may want to consider checking both keyCode
and/or charCode
, as each works in a specific set of browsers. A simple way to be sure we're getting a value that's consistent is to do something like this:
var keycode = event.keyCode || event.charCode;
In the event that event.keyCode
won't work, charCode
will be used instead.
The solution:
If you simply want to ignore the condition that I pointed out as the problem, then just remove it:
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
return false;
}
That being said, your question doesn't say what your desire is... at all. It simply says that what you have "doesn't work for the characters mentioned".
Additional info:
As a side note, I'd be remiss if I didn't point out that your code is not exactly... friendly, for lack of a better word. An elegant way of resolving this is to replace condition lists with named functions, so the purpose and result is much more discernible, like so:
Bad:
if (sunny || not raining and warm || not(cloudy and raining) || not cold)
Good:
if (weatherIsNice(...))
Applied in your case it may be something like
function characterIsAllowed(keycode) {
if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105)) {
return true;
} else {
return false;
}
}
function validate(event) {
var keycode = event.keyCode || event.charCode;
if (characterIsAllowed(keycode)) {
return false;
}
}
Or, simplified one step further...
function characterIsAllowed(keycode) {
return (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57) && (keycode < 96 || keycode > 105))
}
function validate(event) {
var keycode = event.keyCode || event.charCode;
return !characterIsAllowed(keycode);
}