Create a Masked Input Control (cont.)

Blocking Keystrokes
The obvious first step in creating a data-masked control is to detect that a keystroke has occurred. Fortunately, all the target browsers support the keypress event, for example:

   <input type="text" onkeypress="alert('key pressed!')" >
Whenever a user presses a key, the browser executes the event handler assigned to the onkeypress event. You'll focus most of your efforts on the onkeypress event handler.

Now that you know how to detect a keypress event, the next step is to be able to block that key from affecting the current contents of the textbox. Although all three browsers boast of having their own ways to block events, the simplest way is to return a value of false to the keypress event. That technique works in all three target browsers, though you won't find it documented for IE or NS6.

For example, here's a simple function that returns false to the event:

   function doNothing() {
     return false;
   }
Now, assign this function to the onkeypress event. Note that because you want to return the function return value (false) to the event, you must assign the event handler to the value returned from the function, for example:

   <input type="text" name="txtExample" 
      onkeypress="return doNothing()">
This code blocks all keystrokes from appearing in the textbox in all three target browsers. You can test it in Example 1. The problem, of course, is that you want to allow some keystrokes to go through—the numbers. That means you have to determine which key has been pressed and whether you want to allow it to alter the contents of the textbox. Once again, the different browsers offer distinct methods of determining which key has been pressed.

Determining the Pressed Key
The best method to determine which key was pressed is to derive the key from a keycode (the ASCII code for a character). When the keypress event fires it returns a keycode to the client. That keycode maps directly to the key that was pressed. To get the character associated with a given keycode, use the fromCharCode() method of the String object. You need to check the returned character to see if its valid for the numeric textbox.

NS4 and NS6 both use the event object's which property to return the keycode. IE returns the keycode in the event object's keyCode property.

You want to make a function that gets the character string of the pressed key.

   function maskKeyPress(objEvent) {             
     var iKeyCode, strKey;
   
     if (isIE) {
       iKeyCode = objEvent.keyCode;
     } else {
       iKeyCode = objEvent.which; 
     }
     strKey = String.fromCharCode(iKeyCode);
     alert("KeyCode = " + iKeyCode + "\nCharacter ="
       + strKey);
   }
Note that this function takes one argument, objEvent. You can pass the browser's event object using:

   <input type="text" name="txtExample" onkeypress="return maskKeyPress(event)">
Run Example 2. Note that when you type into the textbox, you receive an alert that tells you the keycode of the key that was pressed and the character that corresponds to the key. The next step is to test this returned character for its validity in the textbox.

This is where you can take advantage of JavaScript regular expressions. Pattern matching is an important part of masking data, and regular expressions are an incredibly efficient way to check for valid data without the need for multiple if-then-else statements.

Without going too much into an explanation of regular expressions, the following regular expression, \d, matches only numeric characters (0-9).

   var reValidChars = /\d/;
When the user enters a character that matches the pattern specified in reValidChars you allow it into the textbox; otherwise ignore the character. You can keep the alert used in the previous example, but this time display it only when an invalid character is detected.

Author Note: I've used an alert for demonstrative purposes, but you can modify the code to give the user some other indication that an error occurred, such as playing a sound, or showing a message next to the textbox. After notifying the user of the problem, the function returns a value of false, to prevent the character from being entered into the textbox.

Here's the changed maskKeyPress function:

   function maskKeyPress(objEvent) {             
     var iKeyCode, strKey;
   
     if (isIE) {
       iKeyCode = objEvent.keyCode;
     } else {
       iKeyCode = objEvent.which; 
     }
     strKey = String.fromCharCode(iKeyCode);
     
     if (!reValidChars.test(strKey)) {
       alert("Invalid Character Detected!\nKeyCode = " 
         + iKeyCode + "\nCharacter =" + strKey);
       return false;
     }
   }
Try Example 3. This time, you can type in numbers, but anything else fires the alert. But so far you have dealt with only the first item in the list of textbox behaviors. What about the Backspace key? In IE, it works fine, but when you press the Backspace key in NS4 or NS6 using Example 3, you'll see the invalid character alert. The Backspace key fires the keypress event as well. The code currently blocks the Backspace key.

Before going any further, the third behavior in the list, the Enter key, has the same problem. The Enter key also fires the keypress event. Because this problem is similar to that of the Backspace key, you can solve both in the same way.


Exploring Textbox Behavior

Dealing with Special Keys

Introduction Exploring Textbox Behavior Blocking Keystrokes
Dealing with Special Keys Dealing with Cut, Copy, Paste, and Undo Don't Forget Paste Validation
Polishing the Mask    


 






 TALK BACK
Creating a masked edit text box in DTHML is not as straightforward as it seems at first. Do you know of other masked edit examples? Join the discussions at web.dhtml.scripting to get answers, make comments, or help others with their problems.
Click here to Join
Get the Code

MSDN DHTML Events Reference

MSDN DHTML Input Element Reference

Mozilla DOM Event Interface

Netscape DevEdge, "Form Validation with JavaScript 1.2 Regular Expressions"

Netscape DevEdge, "Form Validation with JavaScript 1.0"

MSDN Behaviors Reference





 
Sponsored Links

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map
Jupiterweb networks

internet.comearthweb.comDevx.comClickZ

Search Jupiterweb:

Jupitermedia Corporation has four divisions:
JupiterWeb, JupiterResearch, JupiterEvents, and JupiterImages

Copyright 2004 Jupitermedia Corporation All Rights Reserved.
Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Jupitermedia Corporate Info | Newsletters | Tech Jobs | E-mail Offers

Copyright Information/Privacy Statement