简体   繁体   中英

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

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM