【发布时间】:2011-06-18 15:48:57
【问题描述】:
单击按钮时如何使用 JSF 跳过 JSR-303 Bean 验证?
一个有点长的问题来解释一些方法......考虑一个表格中的列表:
<h:form id="form">
<h:commandButton value="Add row">
<f:ajax execute="foo" listener="#{bean.add()}" render="foo" />
</h:commandButton>
<h:dataTable id="foo" var="foo" value="#{bean.foos}">
<h:column>
Name: <h:inputText id="field" value="#{foo.name}" required="true" />
<h:messages for="field" />
</h:column>
<h:column>
<h:commandButton value="Remove">
<f:ajax execute=":form:foo" listener="#{bean.remove(foo)}" render=":form:foo" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
当用户单击添加或删除行时,该操作应在未经验证的情况下执行。问题是,JSF 重新呈现整个列表并尝试验证它。如果有未验证的草稿更改,则会发生验证错误,并且永远不会调用侦听器方法(因为验证失败会阻止这种情况发生)。但是,将immediate="true" 添加到 f:ajax 允许方法执行,尽管存在验证错误。但是,仍然会出现验证错误,并在此处显示。
我看到两个选项:
1) 使用 immediate="true" 并且不显示验证错误
对于非验证按钮,设置 immediate="true" 并为 h:messages 设置:
<h:messages rendered="#{param['SHOW_VALIDATION']}" />
然后设置保存按钮(实际上应该尝试保存表单)以发送该参数:
<h:commandButton>
<f:param name="SHOW_VALIDATION" value="true" />
</h:commandButton>
这会导致验证发生,但消息根本不显示,除非存在 SHOW_VALIDATION 参数。
2) 有条件地在 facelets 中声明验证:
<h:inputText>
<f:validateRequired disabled="#{!param['VALIDATE']}" />
</h:inputText>
和保存按钮:
<h:commandButton>
<f:param name="VALIDATE" value="true" />
</h:commandButton>
这会导致字段仅在存在 VALIDATE 参数时才有效(=按下保存按钮时)。
但这些似乎有点像黑客。我怎样才能简单地使用 JSR-303 Bean Validation 但在声明时跳过它?
【问题讨论】:
-
嗯,除了 JSR-303 和带有 JSF 的 facelets 之外,我还没有尝试过任何其他验证解决方案。我认为这个问题与 JSF 相关,而不是 JSF-303 的错——就像他们忘记了“本机”支持在 JSF 中跳过验证。这似乎有很多混乱......
标签: jsf jsf-2 facelets bean-validation