Sunday, 8 March 2015

When your web page includes a form in which users enter data, it is often a good idea to ensure that the data entered into each field is correct. For example, a field that asks for someone’s year of birth should not have letters or punctuation marks entered into it. Likewise a first name field should be restricted to letters. You can validate user input after the fact, as explained later in the chapter “Validating User Form Input”. Sometimes, however, it is better to prevent improper input in the first place by restricting the characters that a user can enter into a text box field.
For example, a “number only” field would accept numbers, but if the user pressed a non number key, it would be ignored. The technique that we will show you relies on a field’s onkeypress event. As you might expect, this event occurs whenever the user presses a key when the field has the focus. The event procedure calls a function that looks at the key that was pressed. If the key is acceptable, the function will return true, which lets the text box to reject the keystroke, effectively blocking the character

The input element must be coded with the onkeypress event as follows:

<input type=‘text’ onkeypress=”return numbersOnly(event)”>

The event argument that is passed to the numbersOnly() function is a reference to the action – the key press – that triggered the event. The function can extract the character that was entered from this object. The numbersOnly() function is shown in Example below:

function numbersOnly(evt)
{
evt = (evt) ? evt : event;
var c = (evt.charCode) ? evt.charCode ; ((evt.keyCode) ?
evt.keyCode : ((evt.which) ? evt.which : 0));
if (c&gt:31 && (c< 48 | | c > 57))
{
alert(“Nembers only are allowed in this field.”);
return false;
}
retun true;
}

The first two lines of the above function will look strange to you. We are not going to explain them beyond saying that they are required to extract the value of the character that was entered from the event object that is passed to the function. The remainder of the function is straight-forward. It accepts only characters with values in the range 48-57, witch are the characters 0-9. By also accepting characters with values less than 31, the function passes through backspace and other editing keys.

This function accepts only the digits 0-9. If you want to accept negative numbers or numbers with a decimal point and minus sign characters. By modifying the range of character values accepted, you can also create functions that accept letters only, lowercase letters only, or whatever you want as per the needs.

0 comments:

Post a Comment