单个输入字段的自定义 JSF 验证器消息 [英] Custom JSF validator message for a single input field
问题描述
我想为不同输入字段的每个验证器提供不同的验证消息.
I'd like to have different validation messages for every validator for different input fields.
在 JSF 中是否可以为每个输入字段的单个验证器(例如
)提供不同的验证消息?
Is it possible in JSF to have a different validation messages for a single validator (e.g. <f:validateLongRange>
) for every input field?
推荐答案
有以下几种方式:
最简单的,只需设置
validatorMessage
属性即可.
<h:inputText ... validatorMessage="Please enter a number between 0 and 42">
<f:validateLongRange minimum="0" maximum="42" />
</h:inputText>
但是,当您使用其他验证器时,也会使用此方法.它将覆盖附加到输入字段的其他验证器的所有消息,包括 Bean 验证.不确定这是否会形成问题.如果是这样,请前往以下方式.
However, this is also used when you use other validators. It will override all messages of other validators attached to the input field, including Bean Validation. Not sure if that would form a problem then. If so, head to following ways.
创建扩展标准验证器的自定义验证器,例如 LongRangeValidator
在您的情况下,捕获 ValidatorException
并使用所需的自定义消息重新抛出它.例如
Create a custom validator which extends the standard validator, such as LongRangeValidator
in your case, catch the ValidatorException
and rethrow it with the desired custom message. E.g.
<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));
}
}
}
使用 OmniFaces
允许在每个验证器的基础上设置不同的验证器消息:
Use OmniFaces <o:validator>
which allows setting a different validator message on a per-validator basis:
<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>
另见:
- 更改默认消息验证错误:需要值"只是需要值"
- 如何自定义 JSF 转换消息必须是由一位或多位数字组成的数字"?
- JSF 中的国际化,何时使用消息包和资源-捆绑?
- JSF 转换器资源包消息
这篇关于单个输入字段的自定义 JSF 验证器消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!