Primefaces自定义验证消息

5

如何在使用Prime Faces消息标记时显示自定义验证消息?

假设我有一个名为Description的字段,我想获得以下消息:

Description:请输入值。

这里Description是字段名称,所以我的真正要求是

formId:inputId:请输入值。

但是目前我得到的是:

Description: 验证错误:值为必填项。

我的代码:

<p:messages id="message" />
<p:inputText id="updatedescription" value="#{equipTemplateBean.equipmentSpecificationsVO.description}" requiredMessage="Please enter Description"                                           required='true'                         
</p:inputText>

请建议如何做到这一点。

使问题更易读,并修正了小的语法错误。 - dingo_d
似乎你的 equipTemplateBean.equipmentSpecificationsVO.description 的默认值是 null,请尝试给它赋一个值并查看结果。 - cristianhh
这不是PrimeFaces消息,而是JSF消息。https://dev59.com/0Gkv5IYBdhLWcg3wtS4N - Kukeltje
2个回答

13
请考虑我的最小示例,当提交为空时,显示自定义错误消息"This field is required.": page.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:p="http://primefaces.org/ui">
    <f:view>
        <h:head/>
        <h:body>
            <h:form>
                <p:inputText id="input"
                             required="true"
                             requiredMessage="This field is required."/>
                <p:message for="input"/>

                <p:commandButton process="input"
                                 update="@form"/>
            </h:form>
        </h:body>
    </f:view>
</html>

1

正如您在mojarra repo文件中所看到的:jsf-api/src/main/java/javax/faces/Messages.properties,第80行,您收到的验证消息是由此属性定义的:

javax.faces.component.UIInput.REQUIRED={0}: Validation Error: Value is required.

您可以创建自己的消息属性文件来覆盖PrimeFaces默认键,并放置:

javax.faces.component.UIInput.REQUIRED={0}: Please enter value.

这是您想要的消息。

要使用此属性文件,请配置JSF的上下文文件,添加一个application xml节点,如下所示:

<application>
  <message-bundle>path.to.your.PropertiesMessageFile</message-bundle>
</application>

希望能对你有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接