简体   繁体   中英

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

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);
        }
    });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM