如果实体的所有字段均为空,如何跳过Bean验证? [英] How can I skip bean validation if all fields for the entity are empty?
问题描述
我有一个这样的地址实体:
I have a address entity like this:
@Entity
public class Address implements java.io.Serializable {
@Id @GeneratedValue(strategy = IDENTITY)
private Long id;
@Size(max = 100)
private String street;
@Size(max = 15)
private String nr;
@Field
@Size(min = 1, max = 20) @NotBlank
private String city;
}
这是其他几个实体的一部分.对于一个这样的实体,地址是可选的. 我有一个视图,我们的用户可以通过几个表单输入(包括几个地址字段)来编辑整个实体.
This is part of several other entities. For one such entity the address is optional. I have a view where our users can edit the whole entity via several form inputs, including several address fields.
为了能够编辑地址,我用一个空的地址实体初始化了父实体.
To be able to edit the address, I initialize the parent entity with an empty address entity.
现在的问题是:当所有地址字段为空时,我不想在实体上保留Address
.为此,如果(且仅当)Address
的所有字段为空时,我需要跳过对实体的验证.如何以最优雅的方式做到这一点?
Now the problem is: I don't want to persist an Address
on the entity when all address fields are empty. For that to work, I need to skip validation for the entity if (and only if) all fields of Address
are empty. How do I do that in the most elegant way?
我目前正在做的是完全跳过对提交按钮的<o:validateBean disabled="true" />
与bean验证,如果地址为null
,则将其设置为null
.但这听起来像是完全破解,因为它在 all 情况下禁用了 all 验证.我该怎么做?
What I'm currently doing is to skip bean validation altogether with <o:validateBean disabled="true" />
for the submit button, setting the address to null
if it comes out empty. But this sounds like a total hack as it disables all validation in all cases. How can I do better?
推荐答案
您可以在<f:validateBean>
(和<o:validateBean>
)的disabled
属性中使用EL.您可以使用EL来检查是否已填写任何这些字段.您可以使用binding
属性引用EL中的组件.您可以通过检查与组件的客户端ID关联的请求参数的值来检查是否已填写字段.
You can just use EL in disabled
attribute of <f:validateBean>
(and <o:validateBean>
). You can use EL to check if any of those fields have been filled. You can use binding
attribute to reference a component in EL. You can check if a field has been filled by checking the value of the request parameter associated with component's client ID.
然后,要在#{addressIsEmpty}
评估true
时在那些字段上禁用bean验证,使用<f:validateBean>
而不是<o:validateBean>
会更容易,因为前者可用于包装多个输入组件.
Then, to disable bean validation on those fields when #{addressIsEmpty}
evaluates true
, it's easier to use <f:validateBean>
instead of <o:validateBean>
as the former can be used to wrap multiple input components.
因此,这应该做到:
<c:set var="addressIsEmpty" value="#{empty param[street.clientId] and empty param[nr.clientId] and empty param[city.clientId]}" />
<f:validateBean disabled="#{addressIsEmpty}">
<h:inputText binding="#{street}" value="#{bean.address.street}" />
<h:inputText binding="#{nr}" value="#{bean.address.nr}" />
<h:inputText binding="#{city}" value="#{bean.address.city}" />
</f:validateBean>
<o:validateBean>
仅在您打算基于每个输入或每个命令进行控制时更易于使用.
The <o:validateBean>
is only easier to use if you intend to control it on a per-input or per-command basis.
这篇关于如果实体的所有字段均为空,如何跳过Bean验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!