Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only numbers in textbox in GWT?

Tags:

gwt

I have a requirement where i need to allow only numbers in text box. if user tries to enter any other character other than numbers then we need to cancel the event. Please help me how to achieve this?

Thanks!

like image 476
user1016403 Avatar asked Nov 07 '11 12:11

user1016403


3 Answers

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.

like image 58
toman Avatar answered Oct 21 '22 13:10

toman


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();
        }
    }
like image 35
bmoran Avatar answered Oct 21 '22 14:10

bmoran


class NumbersOnly implements KeyPressHandler {

        @Override
        public void onKeyPress(KeyPressEvent event) {
            if (!Character.isDigit(event.getCharCode()) 
                    && event.getNativeEvent().getKeyCode() != KeyCodes.KEY_TAB 
                    && event.getNativeEvent().getKeyCode() != KeyCodes.KEY_BACKSPACE){
                ((IntegerBox) event.getSource()).cancelKey();
            }
        }
    }
like image 7
tumbudu Avatar answered Oct 21 '22 13:10

tumbudu