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>
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With