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. } ... }