|
||
| Inside Technique : Custom Input Validation : The Code - Part I Below is the complete checkNumber() function. We are going to take the next two pages giving you a tour
through the techniques used in this code.
The checkNumber function takes the element as an argument. This allows us to reuse the checkNumber function for any input control on the form. The this is a keyword that passes a reference of the current element or object. The first test the checkNumber function performs is to determine whether the browser supports the createTextRange method. This helps
distinguish not only between the Internet Explorer and Netscape but between the different platforms of Internet Explorer 4.0. The TextRange object
is a feature that may not be supported across all platforms of Internet Explorer. The test is performed in two steps: first
we test if the body object is supported (this eliminates Netscape), and second we test whether the TextRange object is supported.
If this test passes, then we start the real work. The first test is to see if a number of decimal point was actually entered.
If not, then we should not spend any cycles actually testing the key:
The keyCode property on the event object returns the ASCII value of the typed key. The fromCharCode converts this ASCII code to the actual string character. Next we use isNan() function tests whether the string is also a valid number or check if the key is a decimal point. If neither are true, we don't event process the value. If you looked at the complete function presented earlier, you will notice there is a small amount of script that runs before the test. To speed up the overall processing.
we cache the number of digits following the decimal point during the first key press. We store this information on the element itself. This technique takes
advantage of the array nature of all objects in JavaScript. You are allowed to add new properties and functions to any object in JavaScript, including built-in ones.
In this example, we added the property, _digits, to the input element if it does not yet exist. Existance is tested by comparing the property to null:
The _digits property is calculated by examining the defaultValue property. The defaultValue property corresponds to the persisted value attribute (the value stored in your HTML file). From this value, we calculate how many digits actual follow the decimal point. This is used when we test the user's input. So far you have seen the code that sets up the real work. Next we walk through using the TextRange object to examine the user's input and compare it to the value already being displayed. Page 1:Custom Input Validation © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |