【问题标题】:JSF2 Cross Field Validation Failure LoopJSF2 跨字段验证失败循环
【发布时间】:2012-07-16 10:29:09
【问题描述】:

我正在开发的应用程序中的要求是,在执行搜索时,用户不应该在不输入州的情况下搜索城市,反之亦然,他们不应该在不输入城市的情况下搜索州。

search.xhtml

<h:inputText id="city" binding="#{city}" value="#{search.city}" validator="#{search.validateCity}">
  <f:attribute name="state" value="#{state}"/>
</h:inputText>

<h:inputText id="state" binding="#{state}" value="#{search.state}" validator="#{search.validateState}">
  <f:attribute name="city" value="#{city}"/>
</h:inputText>

Search.java

public void validateCity(FacesContext context, UIComponent component, Object convertedValue) {
    UIInput stateComponent = (UIInput) component.getAttributes().get("state");
    String state = (String) stateComponent.getValue();
    if(convertedValue.toString().length() > 0) {
        if(state.length() < 1) {
            throw new ValidatorException(new FacesMessage("Please enter State."));
        }
    }
}

public void validateState(FacesContext context, UIComponent component, Object convertedValue) {
    UIInput cityComponent = (UIInput) component.getAttributes().get("city");
    String city = (String) cityComponent.getValue();
    if(convertedValue.toString().length() > 0) {
        if(city.length() < 1) {
            throw new ValidatorException(new FacesMessage("Please enter City."));
        }
    }
}

我已经简化了我的代码,以展示我使用标准跨字段验证方法所做的尝试。但是,我遇到的问题是,在验证阶段,City 和 State 都显示验证错误,我猜是因为这两个验证器相互妨碍,因此造成了失败循环。

有什么办法可以解决这个问题吗?

谢谢。

【问题讨论】:

    标签: validation jakarta-ee jsf-2


    【解决方案1】:

    组件按照在组件树中声明的顺序进行验证。

    当您在尚未验证的组件上调用 UIInput#getValue() 时,它将返回 null。此外,当您在已验证并标记为无效的组件上调用 UIInput#getValue() 时,它将返回 null(或旧模型值)。

    如果您想在验证第一个组件期间获取第二个组件的值,那么您应该使用UIInput#getSubmittedValue() 而不是UIInput#getValue()。您只应记住,这会返回未转换的 String。

    或者,您可以查看OmniFaces &lt;o:validateAllOrNone&gt; 组件。

    <h:inputText id="city" value="#{search.city}" />
    <h:inputText id="state" value="#{search.state}" />
    <o:validateAllOrNone id="cityAndState" components="city state" message="Please fill both city and state." />
    <h:message for="cityAndState" />
    

    【讨论】:

    • 谢谢,BalusC。这解决了问题。
    猜你喜欢
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2014-11-05
    • 2023-03-23
    • 2020-08-03
    相关资源
    最近更新 更多