单个输入字段的定制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中是否可以为每个输入字段的单个验证器(例如<f:validateLongRange>
)使用不同的验证消息?
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转换器资源包消息
- Change the default message "Validation Error: Value is required" to just "Value is required"
- How to customize JSF conversion message 'must be a number consisting of one or more digits'?
- Internationalization in JSF, when to use message-bundle and resource-bundle?
- JSF converter resource bundle messages
See also:
这篇关于单个输入字段的定制JSF验证器消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!