This discussion is archived
2 Replies Latest reply: Apr 8, 2013 11:04 AM by Paul W Smith II RSS

Custom Converter Class To Update inputText Field (Mimic inputDate Defaults)

Paul W Smith II Newbie
Currently Being Moderated
I have a custom converter class attached to an inputText Field used format a phone number that seems to be working as expected, but I would like for the user to see their input change to the formatted value after either tabbing or clicking out of the field similar to the way a default inputDate component will show formatting changes after tabbing or clicking out of the field.

Could anyone provide me with an example of how to get this done... it has be something easy that I am overlooking. Do I need to use a client side converter for this?

Here is my current code:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
/*
* ???Do I need to use a client converter???
* import org.apache.myfaces.trinidad.convert.ClientConverter;
*/

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();
System.out.println("IN CONVERTER GETASOBJECT ORIGINAL PHONE: " + phone);

if (phone.length() == 10) {
phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10);
System.out.println("IN CONVERTER GETASOBJECT NEW PHONE: " + phone);
}
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();
System.out.println("IN CONVERTER GETASSTRING ORIGINAL PHONE: " + phone);

if (phone.length() == 10) {
phone = phone.substring(0, 3) + "-" + phone.substring(3, 6) + "-" + phone.substring(6, 10);
System.out.println("IN CONVERTER GETASSTRING NEW PHONE: " + phone);
}
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;
}
}

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points