【问题标题】:Custom JSF validator message for a single input field单个输入字段的自定义 JSF 验证器消息
【发布时间】:2013-10-02 08:23:40
【问题描述】:

我想为不同输入字段的每个验证器提供不同的验证消息。

在 JSF 中是否可以为每个输入字段的单个验证器(例如 <f:validateLongRange>)提供不同的验证消息?

【问题讨论】:

    标签: validation jsf message


    【解决方案1】:

    有几种方法:

    1. 最简单的,只需设置validatorMessage属性即可。

      <h:inputText ... validatorMessage="Please enter a number between 0 and 42">
          <f:validateLongRange minimum="0" maximum="42" />
      </h:inputText>
      

      但是,当您使用其他验证器时也会使用它。它将覆盖附加到输入字段的其他验证器的所有消息,包括 Bean Validation。不知道那是否会形成问题。如果是这样,请前往以下方式。

    2. 创建一个扩展标准验证器的自定义验证器,例如您的情况下的LongRangeValidator,捕获ValidatorException 并使用所需的自定义消息重新抛出它。例如

      <h:inputText ...>
          <f:validator validatorId="myLongRangeValidator" />
          <f:attribute name="longRangeValidatorMessage" value="Please enter a number between 0 and 42" />
      </h:inputText>
      

      public class MyLongRangeValidator extends LongRangeValidator {
      
          public void validate(FacesContext context, UIComponent component, Object convertedValue) throws ValidatorException {
              setMinimum(0); // If necessary, obtain as custom attribute as well.
              setMaximum(42); // If necessary, obtain as custom attribute as well.
      
              try {
                  super.validate(context, component, convertedValue);
              } catch (ValidatorException e) {
                  String message = (String) component.getAttributes().get("longRangeValidatorMessage");
                  throw new ValidatorException(new FacesMessage(message));
              }
          }
      
      }
      
    3. 使用OmniFaces &lt;o:validator&gt; 允许为每个验证者设置不同的验证者消息:

      <h:inputText ...>
          <o:validator validatorId="javax.faces.Required" message="Please fill out this field" />
          <o:validator validatorId="javax.faces.LongRange" minimum="0" maximum="42" message="Please enter a number between 0 and 42" />
      </h:inputText>
      

    另见:

    【讨论】:

    • 我会选择 2 号,因为我也需要针对不同的验证错误提供不同的消息。你的解决方案让我担心我需要一个超出标准行为的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 2013-06-13
    • 2013-06-05
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多