JSF / PrimeFaces - 如何显示自定义验证器的消息,但不显示同一组件上所需验证的消息



我有一个使用 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 行为。解决您的 问题,您可以使用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>

看看命令按钮的 oncomplete 属性。

最新更新