Ad

Restrict Input In Vaadin IntegerField When Typing

- 1 answer

I have a simple IntegerField in Vaadin 14 with the following settings:

final IntegerField delayField = new IntegerField();
delayField.setMin(0);
delayField.setMax(600000);
delayField.setStep(1000);
delayField.setHasControls(true);

binder.forField(delayField).bind(AppConfiguration::getNotificationDelay, AppConfiguration::setNotificationDelay);

Using the step controls it is not possible to enter values lower than 0 or higher than 600,000. But if I type a value directly, then values like -52 are possible. My understanding was that setMin() and setMax() also works for user input.

How can I automatically restrict the input to the min/max values?

  • If the user types a value < 0, then the value should be set to 0.
  • If the user types a value > 600,000, then the value should be set to 600,000.
Ad

Answer

There is even a simpler solution. Just change the value in the ValueChangeListener:

delayField.addValueChangeListener(event -> {
        if (event.getValue() < 0) {
            integerField.setValue(0);
        } else if (event.getValue() > 600000) {
            integerField.setValue(600000);
        }
    });
Ad
source: stackoverflow.com
Ad