【问题标题】:How to customize JSF validation error message如何自定义 JSF 验证错误消息
【发布时间】:2012-05-11 19:27:30
【问题描述】:

如何自定义验证失败时显示的验证消息?

这是我的代码:

<h:form>
    <p><h:inputText
           id="userNo"
           title="Type a number from 0 to 10:">
       <f:validateLongRange
           minimum="3"
           maximum="6"/>
       </h:inputText>

       <h:commandButton id="submit" value="Submit"
           action="response"/>
    </p>
    <h:message showSummary="true" showDetail="false"
        id="errors1"
        for="userNo"/>
</h:form>

目前消息如下所示:

j_idt10:userNo: Validation Error: Specified attribute is not between the expected values of 3 and 6. 

这不是特别用户友好。

【问题讨论】:

    标签: validation jsf message facelets


    【解决方案1】:

    最简单的方法是在&lt;h:inputText&gt; 标签中设置validatorMessage="my custom message" 属性。

    更高级的方法请阅读这篇文章Customize validation error message in JSF 2.0

    And here a complete Reference to all available message that you can override in JSF 2.0.x

    【讨论】:

    • 令我惊讶的是,无法在属性或其他内容中“即时”设置消息。嗯……
    • 这肯定更有意义。但是,如果我有多个验证器附加到输入并且我想自定义每个验证器的消息怎么办?
    • 那么您需要像我发布的文章中那样覆盖每个验证器的默认消息(在 Messages.properties 文件中)
    【解决方案2】:

    除了 Daniel 的回答之外,您始终可以为您的输入组件使用 label 属性来从错误消息中删除客户端 ID (j_idt10:userNo:)。

    例如与

    <h:inputText id="userNo" title="Type a number from 0 to 10:"
                 label="User number">
      <f:validateLongRange
               minimum="3"
               maximum="6"/>
    </h:inputText>
    

    将产生:

    用户号:验证错误:指定的属性不在 预期值为 3 和 6。

    label属性也可以是el表达式,动态改变这部分错误信息。

    【讨论】:

      【解决方案3】:

      您可以使用输入文本的 validatorMessage 属性。需要的消息使用 requiredMessage 属性,它与验证器消息不同。

      <h:input text required ="true" validatorMessage="Enter user friendly message">
          <f:validateLongRange
              minimum="3"
              maximum="6"/>
      </h:inputText>
      

      【讨论】:

      • 添加说明
      猜你喜欢
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2016-04-18
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多