Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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));
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top