如何在单击按钮时跳过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
参数存在时(=按下保存按钮时),此操作会导致字段仅进行验证。
但这些看起来有点像hack。如何简单地使用JSR-303 Bean Validation,但在声明时跳过它?