单击按钮时,如何使用 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 但在声明时跳过它?