Main Page

Blocking paste

main difference between the two is that
allowChars()
is looking for the
validchars
attribute and
returns
true
only if
sChar
is contained in
sValidChars
. Once again, keep in mind that, if the Ctrl key
is down, the user is performing some sort of function on the text box, so the method has to return
true
.
The method is even used in a similar manner, by returning a value to the
onkeypress
event handler:
<input type=”text” validchars=”0123456789”
onkeypress=”return TextUtil.allowChars(this, event)” />
<textarea rows=”10” cols=”25” validchars=”0123456789”
onkeypress=”return TextUtil.allowChars(this, event)” />
The previous text boxes only allow numerals to be entered (no spaces, letters, or anything else). This
functionality can also be used in a number of creative ways:
<!-- only allow positive integers -->
<input type=”text” validchars=”0123456789”
onkeypress=”return FormUtil.allow(this, event)” />
<!-- only allow “Y” or “N” -->
<input type=”text” validchars=”YN”
onkeypress=”return FormUtil.allow(this, event)” />
Don’t forget the paste
One aspect of text validation that most developers forget about is that the user can paste a value into the
text box. In the
blockCars()
and
allowChars()
methods, it is assumed that the user is typing in the
characters one by one, so they check each character as it comes in. When a user pastes a value, an entire
string is being placed in the text box. You have two ways to deal with validating pasted values: Either
don’t allow pasting or validate the text box when it loses focus.
Blocking paste
Blocking the user ’s capability to paste is very easy to accomplish, but you must cover all bases. A user
can paste in two ways: by clicking Paste on the text box context menu (when right-clicking on it) or by
holding the Ctrl key and pressing V.
In Internet Explorer, the solution is very simple because there is a
paste
event. If the
onpaste
event
handler prevents the default behavior, no paste works no matter how the user tries to do it:
<input type=”text” onkeypress=”return allow(this, event) “ validchars=”0123456789”
onpaste=”return false” />
For other browsers, the process is a little more involved. The first thing to do is block the context menu,
which can be accomplished by returning
false
from the
oncontextmenu
event handler.
<input type=”text” onkeypress=”return allow(this, event) “ validchars=”0123456789”
onpaste=”return false” oncontextmenu=”return false” />
Next, you need to block pasting when the user presses Ctrl and V. The part that makes this easy is that
pressing Ctrl and V causes the
keypress
event to fire, so its possible to use the
allowChars()
and
blockChars()
methods with some modifications:
351
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 351


JavaScript EditorFree JavaScript Editor     Ajax Editor


©