Tutorials - KeyPress validation

Validation using onkeypress and event.keyCode / event.which

Try It - Block Numbers

With JavaScript enabled, numbers cannot be typed into the following text box.

Public Domain

The HTML and JavaScript for Try It - Block Numbers is released to the public domain. Read the Terms of Use for details. The contents of this page are still copyrighted.

Source

Block Numbers - JavaScript

function onKeyPressBlockNumbers(e)
{
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	reg = /\d/;
	return !reg.test(keychar);
}

Block Numbers - HTML

<form>
<input type="text" onkeypress="return onKeyPressBlockNumbers(event);" />
</form>

Explanation

This example will block numbers by returning false to the onkeypress event handler. The conditional statement that chooses e.keyCode or e.which allows the example to work in various browsers including Firefox 1.0.7, Netscape 4.74, Netscape 6.1, Netscape 7.1, Opera 8.02, and IE 6.0.

It should be straightforward, except there are browser differences, because there is no public standard for key events in DOM Level 2.

It used to be a matter between IE using event.keyCode and Netscape 4 using event.which, but now most browsers support event.keyCode. However, as you can tell from the following charts, onkeypress behaves differently in Netscape 4 and Gecko browsers.

Browser Test Charts

All browsers were tested in Windows 2000. The keyCode and which values are all as a result of typing the letter a in a simple script that outputted the values.

For each column that refers to e, the value of e is the event passed in from the event handler.

onkeypress

Browser window.evente.keyCodee.whiche
Firefox 1.0.7 undefined097[object Event]
Netscape 4.74 undefinedundefined97[object Event]
Netscape 6.1 undefined097[object Event]
Netscape 7.1 undefined097[object Event]
Opera 8.02 [object KeyEvent]9797[object KeyEvent]
Internet Explorer 6.0 [object]97undefined[object]

onkeyup and onkeydown

Browser window.evente.keyCodee.whiche
Firefox 1.0.7 undefined6565[object Event]
Netscape 4.74 undefinedundefined97[object Event]
Netscape 6.1 undefined6565[object Event]
Netscape 7.1 undefined6565[object Event]
Opera 8.02 [object KeyEvent]6565[object KeyEvent]
Internet Explorer 6.0 [object]65undefined[object]

Page History

2005-10-25:

2004-09-16:

2001-06-28: First version of the example.

About this page: