JSF:验证两个字段中都提供的值,或者都不验证 [英] JSF: Validate value provided in both fields or none of them

查看:54
本文介绍了JSF:验证两个字段中都提供的值,或者都不验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表示数据范围的字段(从和到)。我需要检查两个字段中的两个字段是否都未填写,因此只有当显示一个验证消息的时间是何时填写一个字段,而不是第二个字段。我怎样才能做到这一点?我用了这个自定义验证器,并将其添加到两个字段中(因为JSF不会验证空字段),但它始终显示它们无效。

I have two fields representing data range ("from" and "to"). I need to check if either both fields are filled on none of them, so only moment there should be validation message shown is when one is filled and not second one. How can I do that? I thied this custom validator and add it to both fields (as JSF doesn't validate empty fields) but it always show that they are not valid.

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。

otherControlId points to second control ID, and I get a control in validator. But otherControlValue is always null.

推荐答案

按组件在组件树中出现的顺序对其进行处理。因此,如果 otherControlInput 在组件树中当前经过验证的组件之后之后出现,则说明该组件尚未处理。然后,您需要通过 UIInput#getSubmittedValue() 而不是 UIInput#getValue()

Components are processed in the order as they appear in the component tree. So if the otherControlInput appears after the currently validated component in the component tree, then it's not processed yet. You would then need to access its (unconverted and unvalidated!) value by UIInput#getSubmittedValue() instead of UIInput#getValue().

Object otherControlValue = otherControlInput.getSubmittedValue();

另一种方法是将验证器放在另一个组件上(该组件出现在树中的最后一个)(而不是当前组件),则可以通过 UIInput#getValue()来获取值。

An alternative is to put the validator on the other component (the one that appears the last in the tree) instead of the current component, then you can get the value by UIInput#getValue().

A完全是另一种选择是让必需属性彼此依赖:

A completely different alternative is to let required attribute depend on each other:

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

这篇关于JSF:验证两个字段中都提供的值,或者都不验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆