I decided to break the task of restricting keyboard input into two parts. The first part defines the valid input, while the second part checks keyboard input against the list of valid input and issues an error message, if desired, if an entry is invalid.
A sample form
Listing A provides a reasonable starting point for restricting input. But there is no reason to stop there—keybDecimal allows for numeric input with a decimal point, and keybDate allows for numeric input with a slash. And of course these examples aren’t written in stone. For instance, if an error message isn’t required for a numeric text object, just change keybNumeric to var keybNumeric = new keybEdit(‘01234567890’);. You can manipulate the keyEdit class to suit your own purposes.
The event handler
One of the great things about writing browser-based applications is that you can use client-side event handlers for the various objects on a page. This can also be the problem with writing browser-based applications, since the wide variety of event handlers can be somewhat overwhelming. For example, three possible event handlers are available for restricting keyboard input for a text element: onKeyDown, onKeyUp, and onKeyPress. Which one should you use? I prefer using the onKeyPress event handler because it returns [Control]C as control-c, instead of control and c separately. The onKeyPress event handler also has the added benefit of ignoring keys like [Tab], [Delete], and [Caps Lock].
Let’s start with an HTML text box named txtCurrentDate:
<INPUT type=text name=txtCurrentDate style=”TEXT-ALIGN: right” onkeypress=”editKeyBoard(this,keybNumeric)”>
Pressing an invalid key produces the message shown in Figure A, while a valid key is accepted and produces no error message.
|Error message dialog box|
This example works perfectly as long as txtCurrentDate is an HTML text box. A slightly different approach is required if txtCurrentDate is a Design Time Control (DTC) in Active Server Page (ASP) development. DTCs make life easier when dealing with server-side issues, but on the client-side, the implementation isn’t as clear because event handlers must be set on page load.
To set the onKeyPress event handler, add the following code to the HTML body tag:
<body onLoad=”document.all.txtTopCustomers.onkeypress = new Function(‘editKeyBoard(this,keybNumeric)’)”>
This has the same end result as the above snippet, but it works with either a DTC or an HTML text box.
Validating the data users can enter in a form reduces the frustration caused by invalid entries. It also helps protect the integrity of the data collected.