Snippets of GWT

Strategy for validating text input in a TextBox during input:

One way to validate that the string being entered into a text box is properly formatted is to reject key changes as the user types, if the resulting string would result in an invalid string. The strategy I’m employing is to add a key press handler and schedule a deferred command: the deferred command then reverts the contents of the text box if the contents are illegal.

Thus:

public class TestEditorBox extends TextBox
{
    public TestEditorBox()
    {
        super();
        
        /*
         * Hang handler off key press; process and revert text of it doesn't
         * look right
         */
        addKeyPressHandler(new KeyPressHandler() {
            @Override
            public void onKeyPress(KeyPressEvent event)
            {
                final String oldValue = getText();
                Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
                    @Override
                    public void execute()
                    {
                        String curVal = getText();
                        if (!validate(curVal)) setText(oldValue);
                    }
                });
            }
        });
    }

    private boolean validate(String value)
    {
         // return true if the string is valid, false if not.
    }
...
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s