Monday, July 30, 2007

Javascript validation using keyCode check

The user is not able to enter certain characters using this approach.

function isDigit(e) {
if (!e) var e = window.event;

var code;
if(e.keyCode) {
code = e.keyCode;
} else if(e.which) {
code = e.which;
// 8-backspace, 9-tab, 13-enter, 46-delete
if (code == 8 || code == 9 || code == 13 || code == 46) {
return true;
var character = String.fromCharCode (code);
return '0' <= character && character <= '9';

<input type="text" name="versionMajor" onkeypress="return isDigit(event);" ../>

onkeydown: Returns a unique integer keyCode representing the the physical key that is pressed. e.g., "1" key on top of keyboard produce "49" whereas in numeric keypad produces "97" since they are different keys. For details.
onkeypress: Returns an integer keyCode representing the Unicode value of the character associated with the key. "1" key produces "49"; Also, for those shift, alt, ctrl combination keys, the combined result is produced such as SHIFT+3 = '#'

The onkeypress (or onkeydown) event hander to respond to a keystroke and to capture the keyCode. If the function returns true and the keystroke produces the character in the textbox. Otherwise, the function returns false and the character is not produced.

The function String.fromCharCode(unicode) is used to convert unicode to ASCII character.

BTW, the comparison of onmousedown and onclick:
onmousedown will trigger when either the left or right (or middle) is pressed. Similarly, onMouseUp will trigger when any button is released. onmousedown will trigger even when the mouse is clicked on the object then moved off of it, while onMouseUp will trigger if you click and hold the button elsewhere, then release it above the object.

onclick will only trigger when the left mouse button is pressed and released on the same object. In case you care about order, if the same object has all 3 events set, it's onmousedown, onMouseUp, then onclick. Each even should only trigger once though.

1 comment:

Neetu Singh said...

this code working properly.Nice Article.Thanks