JSF: <f:convertDateTime type="date" pattern="mm/DD/yyyy"/>

seesee picture seesee · Mar 6, 2013 · Viewed 36.3k times · Source

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.

Answer

BalusC picture BalusC · Mar 13, 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" />