package com.pyramid.misc;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
public class PhoneConverter implements Converter {
public PhoneConverter() {
}
public Object getAsObject(FacesContext facesContext,
UIComponent uiComponent, String value) {
if (value == null || (value.trim().length() == 0))
{
return value;
}
// format phone numbers to display correctly
String phone = value.trim();
if (phone.length() == 10) {
phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10);
}
else if (phone.matches("\\d{10}\\s*\\d+")) {
phone = phone.replaceAll("\\s+", "");
phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10) + " x" + phone.substring(10);
}
return phone;
}
public String getAsString(FacesContext facesContext,
UIComponent uiComponent, Object value) {
String phoneNumber = (String)value;
if (phoneNumber == null || (phoneNumber.trim().length() == 0))
{
return "";
}
String phone = phoneNumber.trim();
if (phone.length() == 10) {
phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10);
}
else if (phone.matches("\\d{10}\\s*\\d+")) {
phone = phone.replaceAll("\\s+", "");
phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10) + " x" + phone.substring(10);
}
return phone;
}
}
2. Register on faces-config.xml file (or faces configuration file)
<faces-config
...
...
<converter>
<description>A Converter for phone number</description>
<converter-id>PhoneConverter</converter-id>
<converter-class>
com.pyramid.misc.PhoneConverter
</converter>
<description>A Converter for phone number</description>
<converter-id>PhoneConverter</converter-id>
<converter-class>
com.pyramid.misc.PhoneConverter
</converter>
...
</faces-config>
3. Use in field:
<af:outputText value="#{row.Phone}" id="ot3">
<f:converter converterId="PhoneConverter"/>
</af:outputText>
格式化方法可以考虑使用Java内置Formatter
回覆刪除