I assume you're using JSF 1.2. Your best bet is then creating a converter which returns null for empty inputs.
public class EmptyToNullConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.trim().isEmpty()) {
if (component instanceof EditableValueHolder) {
((EditableValueHolder) component).setSubmittedValue(null);
}
return null;
}
return value;
}
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
return (value == null) ? null : value.toString();
}
}
Which needs to be registered in faces-config.xml
as follows:
<converter>
<converter-for-class>java.lang.String</converter-for-class>
<converter-class>com.example.EmptyToNullConverter</converter-class>
</converter>
The above is not possible on JSF 1.1 or older because of the inability (by design) to register converters for java.lang.String
.
If it might happen that you're already on JSF 2.0, then just adding the following context parameter to the web.xml
should be sufficient to achieve (less or more) the same. Less or more, because it doesn't trim strings before testing on emptiness.
<context-param>
<param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
<param-value>true</param-value>
</context-param>