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

Hi,

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?

Thanks,
Thorsten

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

Thanks for your hint! I will test it…
Thorsten

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("");
tf.setRegExp("[0-9]
+");
tf.setPreventInvalidTyping(true);

There is one effect that will confuse the users.

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

I wonder if there is a way to make this more user friendly. It would be OK if an empty field resolves to
null
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

tf.setRegExp("[0-9]
*");

instead.

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";
number.setJavaScript(js);

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