SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Custom Input Validation : Setting Up

Before we go into the code, lets first look at how we defined the text box. Since we are dealing with numbers, we added the style to render the text-box right aligned in a monospace font. To define the input rule for the text box, we specified the value attribute as a number. The number of decimal points the initial value has is how many the user is allowed to input. Therefore, the value "1.123" would allow the input of any number out to 3 decimal places. Last, every time a key is pressed, we call the checkNumber function and test if the entered key is allowed. Below we list the text boxes used in our initial demonstration:

<INPUT STYLE="text-align: right; font-family: monospace" 
    TYPE="text" 
    VALUE="0" 
    ONKEYPRESS="return checkNumber(this)">
<INPUT STYLE="text-align: right; font-family: monospace" 
    TYPE="text" 
    VALUE="0." 
    ONKEYPRESS="return checkNumber(this)">
<INPUT STYLE="text-align: right; font-family: monospace" 
    TYPE="text" 
    VALUE="0.0" 
    ONKEYPRESS="return checkNumber(this)">
<INPUT STYLE="text-align: right; font-family: monospace" 
    TYPE="text" 
    VALUE="0.00" 
    ONKEYPRESS="return checkNumber(this)">

The onkeypress event is fired before the key is processed by the browser. Therefore, at the time of the event, the pressed key is not being displayed. In the checkNumber function, we examine this key and decide whether to accept it as valid input. Therefore, it is extremely inportant that the return value of the checkNumber function is returned back to the input control's event handler (eg., return checkNumber(this)). Returning the value from functions is a common ommission when writing form scripts that often causes values and form's to be incorrectly accepted.

Now we are ready to examine the checkNumber() function and how the TextRange object is used to create this example.