The best approach would be to let the user enter whatever they want: β789-555-1234β or β(789) 555-1234β or β7895551234β, and then when the field loses focus, decide that what they typed may be a phone number. If so, you can reformat it as "(789) 555-1234." There are several related questions about how to do such things with regular expressions; just make sure your regular expression accepts the format you are changing the user input to, otherwise it will be very unpleasant for editing.
As an example, see what happens when you type β.5β in the left box of the Microsoft Standard Page Setup dialog box: when you select it, it will change it to β0.5.β
UPDATE: Here is a sample code in GWT for illustration. For this example, suppose the "phoneContainer" element is added to this field. GWT does not give you the complete java.util.regex package, but it gives enough for this:
private void reformatPhone(TextBox phoneField) { String text = phoneField.getText(); text = text.replaceAll("\\D+", ""); if (text.length() == 10) { phoneField.setText("(" + text.substring(0, 3) + ") " + text.substring(3, 6) + "-" + text.substring(6, 10)); } } public void onModuleLoad() { final TextBox phoneField = new TextBox(); RootPanel.get("phoneContainer").add(phoneField); phoneField.addBlurHandler(new BlurHandler(){ public void onBlur(BlurEvent event) { reformatPhone(phoneField); } }); }
source share