【问题标题】:JSF: <f:convertDateTime type="date" pattern="mm/DD/yyyy"/>JSF:<f:convertDateTime type="date" pattern="mm/DD/yyyy"/>
【发布时间】:2013-02-20 19:06:19
【问题描述】:

我有一个使用 convertDateTime 的 JSF 日期组件,它接受“12/12/2013ab”

backing bean 返回“12/12/2013”​​作为日期

我可以知道如何防止用户输入“12/12/2013ab”。它将提示 12/1a/2013 的错误。

【问题讨论】:

  • 请显示您正在使用的组件。普通 JSF 不提供日期组件。
  • 你在使用任何日历组件吗?
  • 如果应用程序在开始和结束时自动修剪坏字符,会不会有问题?否则我建议实现一个 JSF 验证器。这里还有另一个像你一样的问题:stackoverflow.com/questions/3194817/…

标签: java jsf icefaces


【解决方案1】:

提供一个自定义日期转换器,它还检查输入长度。

@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);
    }

}

(请注意patternMM/dd/yyyy 而不是mm/DD/yyyy

然后,而不是

<h:inputText value="#{bean.date}">
    <f:convertDateTime pattern="MM/dd/yyyy" />
</h:inputText>

使用

<h:inputText value="#{bean.date}" converter="myDateTimeConverter" />

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2018-02-01
    • 2020-02-24
    • 2021-12-25
    相关资源
    最近更新 更多