Create form field for numbers only (request for best practice)


I would like to ask if there is a nice way to create a form field which allows only numbers as user input.

This check (if number or not) should be happen before commit() or any form validation / error checks. It should just be impossible to enter non-numbers.

Maybe someone did this before…? Any ideas?


You could use the
CSValidation add-on
with something like setRegExp(“[0-9]
+”) and setPreventInvalidTyping(true).

Thanks for your hint! I will test it…

It took a while but now I implemented this and it works fine.

Just one thing…

As you suggested I use your add-on in this way:

CSValidatedTextField tf = new CSValidatedTextField("");

There is one effect that will confuse the users.

If I start the application with a
in the field and the user decides to fill it with a
then the user normally would use the backspace key to delete the
first. This does not work because if the field is empty it immediately switch back to
The workaround is to move the cursor to the beginning of the field, then type
and then delete

I wonder if there is a way to make this more user friendly. It would be OK if an empty field resolves to
in the form. So you are able to delete the default value and type in another value afterwards.

Any ideas?

Thanks, Thorsten

You could use



I checked this already but the effect was the same. Now I realized that it depends on the browser. I checked with IE7 and Chrome 10: it does not work. Firefox 4 is fine!

It is possible for you to fix this? Do you need a ticket?

Thanks, Thorsten

Oh no, a browser incompatibility.

Hmm, I seem to be having the problem with Firefox 4 as well, unless I’m doing something wrong. I need to examine this further.

Meanwhile, you can use a JavaScript validator as a workaround as follows:

final CSValidatedTextField number = new CSValidatedTextField("Number");
String js = "if (value.match(\"^[0-9]
*$\"))\n" +
        "    null; // Success\n" +
        "else\n" +
        "    \"Fail\";\n";

Note the format of the regular expression in JavaScript. It normally matches substrings as well, so you need the start and end markers.

See the
on-line example

Hi Marko,

this will work for me.

Thanks, Thorsten