Allow only numbers in textbox in GWT?

The following is a more generic approach and allows for code reuse. You can use the NumbersOnly handler for any textbox (of the same class) you wish.

intbox1.addKeyPressHandler(new NumbersOnly());
intbox2.addFocusHandler(new OnFocus());


//inner class
class NumbersOnly implements KeyPressHandler {
        @Override
        public void onKeyPress(KeyPressEvent event) {
            if(!Character.isDigit(event.getCharCode()))
                ((IntegerBox)event.getSource()).cancelKey();
        }
    }

You just have to validate the users input on a certain event. It can be e.g. on every keystroke (KeyPressEvent), when the TextBox loses focus (ValueChangeEvent), on a button press (ClickEvent), and so on. You implement an event handler, e.g. KeyPressHandler and register your implementation with the TextBox. Then in your handler you validate the TextBox value and if it contains something else than numbers, you just return from the method, probably somehow telling the user that the value was invalid.

Something like this:

final TextBox textBox = new TextBox();
textBox.addKeyPressHandler(new KeyPressHandler() {
    @Override
    public void onKeyPress(KeyPressEvent event) {
        String input = textBox.getText();
        if (!input.matches("[0-9]*")) {
            // show some error
            return;
        }
        // do your thang
    }
});

If you have a lot of validation to do, you probably want to introduce some validation framework which saves you from a lot of reinventing the wheel. There may be better alternatives nowadays but personally I have been quite satisfied with the GWT-VL validation framwork.

Tags:

Gwt