Format JSF phone number

The <f:convertNumber> uses DecimalFormat under the covers and this isn't designed with phone numbers in mind.

You'd need to create a custom Converter and do the desired job in getAsString() implementation using the usual String methods such as substring() and friends.

@FacesConverter("phoneConverter")
public class PhoneConverter implements Converter{

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        String phoneNumber = (String) modelValue;
        StringBuilder formattedPhoneNumber = new StringBuilder();

        // ...

        return formattedPhoneNumber.toString();
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        // Conversion is not necessary for now. However, if you ever intend to use 
        // it on input components, you probably want to implement it here.
        throw new UnsupportedOperationException("Not implemented yet");
    }

}

Use it as follows:

<h:outputText value="1234567890" converter="phoneConverter" />

Tags:

Jsf