Validation 单个输入字段的自定义JSF验证器消息

Validation 单个输入字段的自定义JSF验证器消息,validation,jsf,message,Validation,Jsf,Message,对于不同的输入字段,我希望每个验证器都有不同的验证消息 在JSF中,是否可能对每个输入字段的单个验证器(例如,)有不同的验证消息?有几种方法: 最简单的方法就是设置validatorMessage属性 <h:inputText ... validatorMessage="Please enter a number between 0 and 42"> <f:validateLongRange minimum="0" maximum="42" /> </h:i

对于不同的输入字段,我希望每个验证器都有不同的验证消息


在JSF中,是否可能对每个输入字段的单个验证器(例如,
)有不同的验证消息?

有几种方法:

  • 最简单的方法就是设置
    validatorMessage
    属性

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

  • 使用此选项,允许在每个验证器的基础上设置不同的验证器消息:

    <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条,因为我还需要针对不同验证错误的不同消息。你的解决方案证实了我的担忧,即我需要一个超越标准行为的解决方案。
    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));
            }
        }
    
    }
    
    <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>