1

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

搜索.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>

搜索.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 都显示验证错误,我猜是因为两个验证器相互妨碍,因此造成了失败循环。

有没有我可以用来解决这个问题的解决方法?

谢谢。

4

1 回答 1

1

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

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

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

或者,您可以查看OmniFaces <o:validateAllOrNone>组件。

<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" />
于 2012-07-17T15:18:55.593 回答