Main Page

Allowing valid characters

To use this method, insert it into the HTML code for a text box (either
<input/>
or
<textarea/>
) along
with the
invalidchars
attribute:
<input type=”text” invalidchars=”0123456789”
onkeypress=”return TextUtil.blockChars(this, event) “ />
<textarea rows=”10” cols=”25” invalidchars=”0123456789”
onkeypress=”return TextUtil.blockChars(this, event)” />
This one function can be used to block characters in a variety of useful ways:
<!-- block all numbers -->
<input type=”text” onkeypress=”return FormUtil.block(this, event)”
invalidchars=”0123456789” />
<!-- block all uppercase letters -->
<input type=”text” onkeypress=”return FormUtil.block(this, event) “
invalidchars=”ABCDEFGHIJKLMNOPQRSTUVWXYZ” />
<!-- block all lowercase letters -->
<input type=”text” onkeypress=”return FormUtil.block(this, event)”
invalidchars=”abcdefghijklmnopqrstuvwxyz” />
<!-- block spaces -->
<input type=”text” onkeypress=”return FormUtil.block(this, event)”
invalidchars=” “ />
Allowing valid characters
Naturally, the other method of restricting user input is to only allow certain characters in a text box.
Once again, the easiest way to accomplish this is to add an HTML attribute to a text box:
<input type=”text” validchars=”0123456789” />
This example would allow the numbers 0 through 9 only, and no other characters. Naturally, you’ll need
to have an
allowChars()
method that does the opposite of the
blockChars()
method:
TextUtil.allowChars = function (oTextbox, oEvent) {
oEvent = EventUtil.formatEvent(oEvent);
var sValidChars = oTextbox.getAttribute(“validchars”);
var sChar = String.fromCharCode(oEvent.charCode);
var bIsValidChar = sValidChars.indexOf(sChar) > -1;
return bIsValidChar || oEvent.ctrlKey;
};
As you can see, the
allowChars()
has a lot in common with
blockChars()
: It accepts the text box and
the event object as arguments; it formats the event object using
EventUtil.formatEvent()
; it stores
the character that will be entered into the text box in a variable using
String.fromCharCode()
. The
350
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 350


JavaScript EditorFree JavaScript Editor     Ajax Editor


©