I have a JSF date component using convertDateTime and it accepts "12/12/2013ab"
the backing bean returns "12/12/2013" as date
may I know how can I prevent user from entering "12/12/2013ab". It will prompt an error for 12/1a/2013.
Provide a custom date converter which also checks the input length.
@FacesConverter("myDateTimeConverter")
public class MyDateTimeConverter extends DateTimeConverter {
public MyDateTimeConverter() {
setPattern("MM/dd/yyyy");
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value != null && value.length() != getPattern().length()) {
throw new ConverterException("Invalid format");
}
return super.getAsObject(context, component, value);
}
}
(please note that the pattern is MM/dd/yyyy
and not mm/DD/yyyy
)
Then, instead of
<h:inputText value="#{bean.date}">
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:inputText>
use
<h:inputText value="#{bean.date}" converter="myDateTimeConverter" />