我想为不同输入字段的每个验证器提供不同的验证消息。
在JSF中是否可以<f:validateLongRange>
为每个输入字段的单个验证器(例如)使用不同的验证消息?
有几种方法:
最简单的,只需设置validatorMessage
属性。
<h:inputText ... validatorMessage="Please enter a number between 0 and 42">
<f:validateLongRange minimum="0" maximum="42" />
</h:inputText>
但是,当您使用其他验证器时,也会使用此方法。它将覆盖附加到输入字段的其他验证器的所有消息,包括Bean验证。不知道那是否会构成问题。如果是这样,请遵循以下方法。
创建一个自定义验证器,以扩展标准验证器,例如,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));
}
}
}
使用OmniFaces <o:validator>
,它允许在每个验证者的基础上设置不同的验证者消息:
<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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句