Numberic TextBox

Hi,
I want to allow Numberic values only in TextBox. Could you please how to do that.

TextField amountTxt = new TextField()

Thanks
Sakthi

You could try to extend the TextField using a TextChangeListener.

public class NumberTextField extends TextField implements TextChangeListener {

    private String lastValue;

    public NumberTextField() {
        lastValue = "";

        setImmediate(true);
        setTextChangeEventMode(TextChangeEventMode.EAGER);
        addTextChangeListener(this);
    }


    @Override
    public void textChange(TextChangeEvent event) {
        String text = event.getText();

        if (text.isEmpty() || isDouble(text)) {
            lastValue = text;
        }
        else {
            setValue(lastValue);
        }
    }


    private boolean isDouble(String s) {
        boolean result = true;
        try {
            Double.parseDouble(s);

            if (s.endsWith("d") || s.endsWith("f")) {
                result = false;
            }
        }
        catch (NumberFormatException e) {
            result = false;
        }

        return result;
    }
}

There are a lot of ways to do that depending on your Vaadin/Java skills and what you want to do exactly.
Some of them are:

  • Validators
  • Manually validating using TextChangeListener as described above
  • client side extension so that either you can send an error immediately or make it so that non-numeric values won’t even show up in the Textfield

There should be enough documentation out there for all of those options.