How to validate number format TextField in wicket?

10,524

Solution 1

The problem you are facing is related to the way Wicket works. First it converts input text into a model object and then it performs validation.

Thus, you have to use RangeValidator instead of StringValidator

IModel<Integer> model =
    new PropertyModel<Integer>(personModel, "age");
Component ageField = new TextField<Integer>("age", model);
add(ageField).add(RangeValidator.<Integer>range(0, 99));

Note I've changes Long to Integer as I believe saving age as Long is not practical.

Also note that link to NumberValidator is for Wicket 1.4, while you are using Wicket 6. Wicket 6 is a large API change comparing to previous versions.

Solution 2

For future reference please have a look at NumberTextField<N>

In Op's case, you could do more easily like:

IModel<Integer> model = new PropertyModel<Integer>(personModel, "age");
add(new NumberTextField<Integer>("age", model).setMinimum(0).setMaximum(99));
Share:
10,524
victorio
Author by

victorio

Updated on June 04, 2022

Comments

  • victorio
    victorio almost 2 years

    In my maven-wicket (6.10) application I have a TextField, which has an Integer type property model. I want to set a maximum length for numberts to type into this TextField. (for example the user should write maximum 2 characters to the "age" text field)

    I have tried this code:

    add(new TextField<>("age",new PropertyModel<(personModel,"age"))
        .add(StringValidator.maximumLength(2)));
    //age is an Integer value from a Person class, personModel is "IModel<Person>" type
    

    but I got this exception:

    java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
        at org.apache.wicket.validation.validator.StringValidator.getValue(StringValidator.java:87)
        at org.apache.wicket.validation.validator.StringValidator.getValue(StringValidator.java:59)
        at org.apache.wicket.validation.validator.AbstractRangeValidator.validate(AbstractRangeValidator.java:107)
        at org.apache.wicket.markup.html.form.FormComponent.validateValidators(FormComponent.java:1523)
    

    So if the property model is not string type, I cannot use StringValidator. I have found examples, which use NumberValidator (validators), but I cannot resolve NumberValidator. I have only these validators in the source: validation source How could I use number validator? Or am I missing something, maybe form the pom.xml's dependencies for wicket?

  • victorio
    victorio about 10 years
    Thanks, it looks like good! But I made my own NumberFormatValidator, but your answer is good! :-)
  • divanov
    divanov about 10 years
    Sure, defining your own validator is another way of doing it. This is the only solution, for example, if validated value must be in one of two ranges or odd.