代码之家  ›  专栏  ›  技术社区  ›  Migol

JSF:验证两个字段中提供的值,或者不验证其中任何一个字段

  •  2
  • Migol  · 技术社区  · 15 年前

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
      String otherControlId = (String) component.getAttributes().get("otherControlId");
      UIInput otherControlInput = (UIInput) context.getViewRoot().findComponent(otherControlId);
      Object otherControlValue = otherControlInput.getValue();
      if ((value == null && otherControlValue != null) || (value != null && otherControlValue == null)) {
     //show message
      }
    }
    

    otherControlId指向第二个控件ID,我在validator中获得一个控件。但是otherControlValue总是空的。

    1 回复  |  直到 15 年前
        1
  •  2
  •   BalusC    15 年前

    组件按其在组件树中出现的顺序进行处理。所以如果 otherControlInput 出现 组件树中当前已验证的组件,则尚未对其进行处理。然后需要访问它的(未转换和未验证!)价值依据 UIInput#getSubmittedValue() 而不是 UIInput#getValue() .

    Object otherControlValue = otherControlInput.getSubmittedValue();
    

    UIInput#getValue() .

    required 属性相互依赖:

    <h:inputText binding="#{from}" value="#{bean.from}" required="#{not empty to.submittedValue}" />
    <h:inputText binding="#{to}" value="#{bean.to}" required="#{not empty from.value}" />
    
    推荐文章