Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format JSF phone number

Tags:

jsf

I am storing a phone number as a string in our database. It would be stored like "1234567890". I want to display that to the user and format it like (12) 3456-7890 How can I do this with JSF 2.0? I tried the following, but it doesn't work:

<h:outputText value="1234567890">
<f:convertNumber pattern="(##) ####-####"/>
</h:outputText>
like image 693
CaptainMorgan Avatar asked Nov 18 '13 01:11

CaptainMorgan


1 Answers

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" />
like image 181
BalusC Avatar answered Sep 28 '22 18:09

BalusC