【问题标题】:JSF / PrimeFaces - How to display message for custom validator but not for required validation on the same componentJSF / PrimeFaces - 如何显示自定义验证器的消息,但不显示同一组件上所需的验证
【发布时间】:2018-09-01 10:38:45
【问题描述】:

我有一个使用 PrimeFaces 的 JSF2 实现。我正在使用<p:selectOneRadio /> 组件。当用户在收音机组件中选择“否”时,我想显示一条自定义消息。为此,我创建了一个自定义验证器,并且与消息组件一起一切正常。但是,该组件也是必需的。我不希望所需组件的“需要值”验证错误出现在消息组件中。在这种情况下,我只希望突出显示字段和标签。

所以,问题是:如何指定给定的<p:message /> 组件仅显示来自我的自定义验证器的错误,而不是来自所需验证器的错误?

我在几年前看到了一个类似问题的答案,它说您可以将消息for 属性设置为实际不存在的组件,然后通过 FacesContext 将消息添加到该组件。比如这样: <p:message for="fooMsg" /> ... FacesContext.getCurrentInstance().addMessage("fooMsg",msg)

但是,这似乎不起作用。 JSF 抛出找不到组件“fooMsg”的错误。

这是我当前的代码。

组件:

<p:outputLabel for="foo" id="foolbl"
    value="Some label text." />
<br />
<p:message for="foo" />
<p:selectOneRadio id="foo" layout="pageDirection"
    widgetVar="fooVar" required="true">
<f:selectItem itemLabel="Yes" itemValue="Yes" />
<f:selectItem itemLabel="No" itemValue="No" />
<p:ajax update="@this foolbl" process="@this" />
<f:validator validatorId="FooValidator" />
</p:selectOneRadio>

验证器:

@FacesValidator("FooValidator")
public class FooValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        if (value != null) {
            String sValue = (String) value;
            if (sValue.trim().equalsIgnoreCase("No")) {
                FacesMessage msg = new FacesMessage("Summary",
                        "Detail");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);

                throw new ValidatorException(msg);
            }
        }
    }

}

【问题讨论】:

    标签: jsf primefaces jsf-2 jsf-2.2 mojarra


    【解决方案1】:

    首先这是默认的 JSF 行为。解决您的 问题,您可以使用 jQuery 检查是否没有选择单选按钮并隐藏其中的消息 案例,例如:

    <h:form id="form">
        <p:outputLabel for="foo" id="foolbl" value="Some label text." />
        <br />
        <p:message id="foomsg" for="foo" />
        <p:selectOneRadio id="foo" layout="pageDirection" widgetVar="fooVar"
            required="true">
            <f:selectItem itemLabel="Yes" itemValue="Yes" />
            <f:selectItem itemLabel="No" itemValue="No" />
            <p:ajax process="@this" update="@this foolbl foomsg" />
            <f:validator validatorId="FooValidator" />
        </p:selectOneRadio>
    
        <p:commandButton process="@this foo" update="foo foolbl foomsg"
            oncomplete="if( !PF('fooVar').checkedRadio.length ) $('#form\\:foomsg').hide();" />
    </h:form>
    

    看看commandButton的oncomplete属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-05
      • 2014-02-21
      • 2014-05-28
      • 2014-08-08
      • 1970-01-01
      • 2019-02-22
      • 2011-09-18
      • 1970-01-01
      相关资源
      最近更新 更多