WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.
Most JSF components have a number of
You can use this to improve the user interaction. For example,
let's say you have a text field which can only contain numbers.
Clearly, you should put a validator on the number field - never
trust client-side validation alone. However, rather than users
having to find out after the submit that they made a mistake they
need to correct, why not prevent them from typing anything other
than a number in the first place?
being entered into a textfield. Here's how: We need to write
whether the given key is valid, and if not, return false - this
will prevent the key from getting added into the textfield.
we can add it to our document by embedding it in a
code in a CDATA section to prevent the XML parser from interpreting
it as anything other than raw data:
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec)
key = window.event.keyCode;
else if (e)
key = e.which;
keychar = String.fromCharCode(key);
// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
else if ((("0123456789").indexOf(keychar) > -1))
// decimal point jump
else if (dec && (keychar == "."))
Alternatively, you can place this code (without the surrounding
and in that case instead of including the large section above,
all you need to do is add the following line in your JSP:
Warning: I have seen some reports in the
that the above XML can get changed into
and if this happens, Internet Explorer fails. I fixed this bug
scriptand some other tags were
getting minimized when they shouldn't) in Creator late last
summer, so this shouldn't happen with the recent updates (and
I can't reproduce it) but be on the lookout for it and let me
know if you see any problems in this area.
Now the final step - select your text field, and bind the
return numbersonly(this, event)
In other words, your JSP for the text field should look something
onkeypress="return numbersonly(this, event)"
Notice how there is also a validator attached to this component.
Don't forget to do server-side validation - that's what counts!
if you want to allow negative numbers (e.g. a minus sign must be allowed).
when the user enters a dot, which we're not taking advantage of here - there's