Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT telephone number masking

Does anyone know how to go about creating field that would perform telephone number format masking, like here (___) ___-____:
http://www.smartclient.com/smartgwt/showcase/#form_masking

like image 231
MatBanik Avatar asked Dec 27 '22 19:12

MatBanik


2 Answers

A better approach would be to let the user type whatever they want: "789-555-1234" or "(789) 555-1234" or "7895551234" and then when the field loses focus decide if what they typed can be a phone number. If so you can reformat it as "(789) 555-1234". There are several related questions about how to do that sort of thing with regular expressions; just be sure your regex accepts the format you're changing the user's input to, otherwise it will be really annoying to edit.

As an example, look what happens when you type ".5" into the left margin field in Microsoft's standard page setup dialog: when you tab out it changes it to "0.5".

UPDATE: Here's sample code in GWT to illustrate. For the sake of this example, assume there's an element called "phoneContainer" to put the text box in. GWT doesn't give you the full java.util.regex package, but it gives enough to do 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);
        }
    });
}
like image 167
gatkin Avatar answered Dec 30 '22 09:12

gatkin


It looks like you'd want to create your own widget that extends the GWT input box and has a default value set to the mask you want. Then you handle the onKeypress event and update the field as needed (making sure to set the cursor position to the correct location).

like image 20
Abdullah Jibaly Avatar answered Dec 30 '22 09:12

Abdullah Jibaly