JSF number format

I save the phone number as a string in our database. It will be stored as "1234567890". I want to show this to the user and format it as (12) 3456-7890 How can I do this with JSF 2.0? I tried the following, but it does not work:

<h:outputText value="1234567890"> <f:convertNumber pattern="(##) ####-####"/> </h:outputText> 
+6
source share
1 answer

<f:convertNumber> uses DecimalFormat under covers, and this is not related to phone numbers.

You need to create a custom Converter and do the job in getAsString() using regular String methods like 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" /> 
+6
source

Source: https://habr.com/ru/post/958279/


All Articles