↑
Main Page
Validating onblur
Validating onblur
If you don’t want to block the user ’s capability to paste, you must validate the input in another way. The
easiest way to do this is to create an
onblur
event handler that won’t let the user move to another field
until the value in the text box is valid. This necessitates two additional methods: one to use with
blockChars()
and one to use with
allowChars()
.
The companion function for
blockChars()
is called
blurBlock()
, and it accepts the text box as its
only argument. Here’s the code:
TextUtil.blurBlock = function(oTextbox) {
var sInvalidChars = oTextbox.getAttribute(“invalidchars”);
var arrInvalidChars = sInvalidChars.split(“”);
for (var i=0; i< arrInvalidChars.length; i++){
if (oTextbox.value.indexOf(arrInvalidChars[i]) > -1) {
alert(“Character ‘“ + arrInvalidChars[i] + “‘ not allowed.”);
oTextbox.focus();
oTextbox.select();
return;
}
}
};
The first step in this method is the same as in
blockChars()
: You must get the invalid characters from
the
invalidchars
attribute. Because all the text in the text box must be validated (not just a single char-
acter), it’s necessary to test for each invalid character individually, so the next step in the method splits
the invalid character string into an array of characters (you’ll recall that using
split()
with an empty
string argument returns an array of the characters). Then, the method loops through each invalid charac-
ter to see if it exists in the text box. When an invalid character is found, an alert is displayed telling the
user that the given character is invalid. The focus is then set back to the text box and its contents are
selected. The method exits at that point, because so long as there is one invalid character, there’s no
need to check for any others (you may also choose to look for all invalid characters before exiting).
This method is inserted into the
onblur
event handler like this:
<input type=”text” onkeypress=”return TextUtil.blockChars(this, event)”
invalidchars=”0123456789” onblur=”TextUtil.blurBlock(this)” />
You must use
onpaste=”return false”
as well as the
allowChars()
and
blockChars()
methods because you cannot block the Ctrl + V keystroke in Internet
Explorer.
353
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 353
Free JavaScript Editor
Ajax Editor
©
→