【问题标题】:JSF how to get in validator information if field is required?如果需要字段,JSF 如何获取验证器信息?
【发布时间】:2016-02-06 04:44:16
【问题描述】:

我的应用程序中的h:inputText 有问题。有些字段可能是必需的,有些则不需要,我想为所有这些字段创建一个自定义验证器,并且找不到如何检查验证器类的信息是 UIComponent 是必需的还是不需要。

输入域代码如下所示:

<h:inputText styleClass="form-control"
         disabled="#{cc.attrs.bean.disableAnswerPosibility(cc.attrs.answer)}"
         value="#{cc.attrs.freeAnswer}"
         requiredMessage="#{msg.fieldRequired}"
         a:requiredForValidator="#{cc.attrs.question.optional}"
         required="#{cc.attrs.question.optional}">
    <f:validator validatorId="stringValidator"/>
</h:inputText>

如您所见,我尝试将此信息作为传递参数传递。它在网页上呈现为真/假,但是当我尝试在验证器类中获取它时,它是某种对象,在网页源中没有显示值,但带有来自 .xhtml 文件的代码。

代码如下:

Object temp = uiComponent.getPassThroughAttributes().get("requiredForValidator");

这是我得到的:

我只需要值 - 布尔值或字符串。有什么建议吗?

【问题讨论】:

  • 您是否尝试评估表达式?
  • 这个问题令人困惑。为什么不检查required 属性?为什么要将其复制到 passthrough 属性中?

标签: validation jsf


【解决方案1】:

在验证器的 validate 方法中,您可以将组件转换为 javax.faces.component.UIInput 并像这样评估其 required 属性。

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        UIInput inputComponent = (UIInput) component;
        if(inputComponent.isRequired()){

        }
    } 

这个验证器显然只适用于UIInput 组件。

【讨论】:

  • 天哪 - 有时我自己也很惊讶...谢谢 :)
猜你喜欢
  • 1970-01-01
  • 2016-12-18
  • 2017-11-19
  • 2019-05-18
  • 1970-01-01
  • 2011-12-20
  • 2011-07-10
  • 2011-10-22
  • 2017-06-07
相关资源
最近更新 更多