我需要FacesMessage为这个组件显示一个,如下所示,

问题是它在 UI 上多次显示,如下所示,

其次,输入的日期40.06.2015是无效的,因此FacesMessage, 但它被转换为10.07.2015. 我不知道如何防止这种情况。任何帮助都受到高度赞赏。我知道它可以setLenient()在DateFormat课堂上轻松处理,但不知何故,在我可以在后台使用之前,UI 组件将其转换为下个月的日期。
附加到该组件的验证器如下:

那么,如何避免多次显示“请以正确格式输入日期”?
我想到了使用h:message而不是h:messages, 并在验证器方法的 catch 块中像这样
FacesContext.getCurrentInstance().addMessage("formId:aboveCompId", message);
Run Code Online (Sandbox Code Playgroud)
但 UI 上没有显示任何内容。有什么建议?
这种方法至少有两个问题。
您将组件绑定到 bean 属性。这些症状表明 bean 不是请求范围的。这是一个非常糟糕的主意。UI 组件本质上是请求范围的,不应在更广泛的范围内绑定为 bean 的属性,否则 JSF 将重用它们而不是创建一个新的。如果你继续这样做,所有标签处理程序(包括验证器绑定)将在同一个 bean 上的请求中一遍又一遍地运行在同一个 UI 组件实例上,因此每次回发都会累积(你会看到每次回发的消息数量越来越多)相同的视图,由相同的验证器重新附加到相同的组件实例引起)。
您在验证器中手动添加人脸消息,而不是在ValidatorException其中抛出人脸消息。因此,JSF 生命周期在验证阶段之后错误地继续,而没有按照规范中止它。
回到具体的功能需求。
至于非宽松的日期转换,只需明确使用<f:convertDateTime>. 如有必要,可以通过converterMessage输入组件的属性自定义转换器消息。
至于日期范围验证,只需等到转换器完成并获取正确的Dateasvalue然后通过Date#before()or进行比较Date#after()。
所以,简而言之,这应该为你做:
private Date startDate;
private Date endDate;
Run Code Online (Sandbox Code Playgroud)
<t:inputCalendar id="startDate" binding="#{startDateComponent}" value="#{bean.startDate}"
renderAsPopup="true" renderPopupButtonAsImage="true"
popupDateFormat="dd.MM.yyyy" popupTodayDateFormat="dd.MM.yyyy"
converterMessage="Please enter date in correct format"
>
<f:convertDateTime pattern="dd.MM.yyyy" />
</t:inputCalendar>
<t:inputCalendar id="endDate" value="#{bean.endDate}"
renderAsPopup="true" renderPopupButtonAsImage="true"
popupDateFormat="dd.MM.yyyy" popupTodayDateFormat="dd.MM.yyyy"
converterMessage="Please enter date in correct format"
>
<f:convertDateTime pattern="dd.MM.yyyy" />
<f:validator validatorId="dateRangeValidator" />
<f:attribute name="startDateComponent" value="#{startDateComponent}" />
</t:inputCalendar>
Run Code Online (Sandbox Code Playgroud)
在下面的第二个“另请参阅”链接中可以找到dateRangeValidator真实且可重复使用的@FacesValidator内容。请注意,第一个组件绑定到视图,绝对不是绑定到bean,并且验证与支持 bean没有紧密耦合。
| 归档时间: |
|
| 查看次数: |
1216 次 |
| 最近记录: |