在我的JSF应用程序中,我想验证只应验证的字段,只有选中SelectOneradio中的一个选项时。
我发现,<f:validator>
有一个属性,称为“禁用”。
我可以用它来检查另一个字段的值吗?
我试过了,但我无法访问我的 bean 中的值。
<h:selectOneRadio value="#{myBean.checkedSelectOneRadioValue}">
<f:selectItems value="#{myBean.valuesForSelectOneRadio}" />
</h:selectOneRadio>
<f:validator validatorId="myValidator" disabled="#{myBean.checkedSelectOneRadioValue == 'TEST'}" />
有没有办法在不编写自己的验证器处理程序的情况下达到这个目标?
谢谢!
最佳答案
<f:validator>
是一个标签处理程序,而不是一个 UI 组件。它的所有属性都是在 View 构建时间而不是 View 渲染时间根据定义评估的。 View 构建时间是 XHTML 文件被解析为可用的 JSF 组件树的那一刻 context.getViewRoot()
.非常相同的 View 通常通过返回 null
在回发到同一 View 中重复使用。/void
在(ajax) Action 中。
因此,您不能让标记处理程序属性依赖于在回发请求期间可以更改的呈现时间属性。一种方法是在自定义验证器本身内部执行该检查。
例如。
<h:inputText>
<f:validator validatorId="myValidator" />
<f:attribute name="radio" value="#{myBean.checkedSelectOneRadioValue}" />
</h:inputText>
和
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (!"TEST".equals(component.getAttributes().get("radio"))) {
return;
}
// Perform actual validation here.
}
您也可以使用 OmniFaces
<o:validator>
反而。它扩展了标准 <f:validator>
使用基于请求的属性评估 EL。<h:inputText>
<o:validator validatorId="myValidator" disabled="#{bean.checkedSelectOneRadioValue == 'TEST'}" />
</h:inputText>
另见 showcase example和 source code相关摘录如下:
@Override
public void apply(FaceletContext context, UIComponent parent) throws IOException {
if (!ComponentHandler.isNew(parent)) {
return;
}
final javax.faces.validator.Validator validator = createValidator(context);
final RenderTimeAttributes attributes = collectRenderTimeAttributes(context, validator);
final ValueExpression disabled = getValueExpression(context, "disabled", Boolean.class);
((EditableValueHolder) parent).addValidator(new javax.faces.validator.Validator() {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (disabled == null || Boolean.FALSE.equals(disabled.getValue(context.getELContext()))) {
attributes.invokeSetters(context.getELContext(), validator);
validator.validate(context, component, value);
}
}
});
}
关于validation - JSF 2.0;验证器标签 "disabled"取决于页面中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9906045/