How can I skip bean validation if all fields for the entity are empty?

妖精的绣舞 提交于 2019-12-01 18:26:15

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.

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.

So, all with all, this should do:

<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>

The <o:validateBean> is only easier to use if you intend to control it on a per-input or per-command basis.

Cross validation of multiple fields can be a tough issue. But in this situation it is not validation per se that bothers you in the first place but rather possibility to nullify some instance on some condition in your bean before you'd persist the entity.

The most straightforward way would be to mark all fields associated with Address entity as required="false" in your view not to care of fields being filled in (or just omit it as it's the default) and do all the checks of, and modifications to the placeholder in your action method, right before calling your EJB service. Like so:

public String save() {
    //do some checks
    if((entity.getAddress().getStreet() == null) && ...) {
        //assign address to null
        entity.setAddress(null);
    }
    entityService.persist(entity);
    return "success";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!