javawicketwicketstuffwicket-7

Allow only whole number in wicket Textfield


I am using a NumberTextField in Wicket 7 and my requirements are

  1. User should be able to enter only a whole numeric char into the textfield and neither a decimal value nor any non-numeric char.
  2. char should not be more than 3 characters long.

But NumberTextField allows the user to input a decimal value. How do I restrict the length of NumberTextField in Wicket 7.


Solution

  • You need to set the type of the field. You can do it in the constructor: NumberTextField(String id, IModel model, Class type) or via setter: field.setType(Integer.class).

    Then you can add validator for the allowed values: field.add(RangeValidator.range(0, 999).

    If you need to have the same validations at the client side then you will need to use JavaScript validation library. You can check https://github.com/code-troopers/wicket-jsr303-parsley and the blog: http://wicketinaction.com/2013/04/server-and-client-side-validation/