我有两个表示数据范围的字段(“从”和“到”)。我需要检查两个字段是否都没有填写,因此只有当一个字段被填写而不是第二个字段时,才会显示验证消息。我怎样才能做到这一点?我偷了这个自定义验证器并将其添加到两个字段(因为 JSF 不验证空字段),但它总是显示它们无效。
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,我在验证器中获得了一个控件。但 otherControlValue 始终为 null。
组件按照组件树中出现的顺序进行处理。所以如果otherControlInput
出现after组件树中当前已验证的组件,则尚未对其进行处理。然后,您需要通过以下方式访问其(未转换且未经验证!)的值:UIInput#getSubmittedValue() http://download.oracle.com/javaee/6/api/javax/faces/component/UIInput.html#getSubmittedValue%28%29代替UIInput#getValue() http://download.oracle.com/javaee/6/api/javax/faces/component/UIOutput.html#getValue%28%29.
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}" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)