在自定义验证器中显示标签

时间:2011-06-19 18:52:02

标签: validation jsf jsf-2 primefaces

我创建了一个实现自定义验证器的新自定义组件。 以下是我如何称呼它:

<p:inputText value="#{MyBean.value}" >
    <f:attribute name="label" value="#{ResourceBean.labels['label']}"/>

    <my:validator error="#{ResourceBean.message['the.error.message']}" 
                  expression="#{ResourceBean.regExp['alphanumeric']}"/>
</p:inputText>

这是验证实现

String val = value == null ? "" : value.toString();

if (!val.matches(getExpression())) {
    throw new ValidatorException(new 
              FacesMessage(FacesMessage.SEVERITY_ERROR,getErrorSummary(),null));

和属性文件中的错误消息:

the.error.message={0}\: is Invalid.

问题是{0}未被错误消息中的标签替换,因此我收到错误消息:

{0}: is Invalid.

任何想法如何解决?

2 个答案:

答案 0 :(得分:5)

您需要使用MessageFormat API,就像JSF在幕后一样。

String message = getErrorSummary();
String label = component.getAttributes().get("label");
String formattedMessage = MessageFormat.format(message, label);
throw new ValidatorException(new FacesException(formattedMessage));

答案 1 :(得分:2)

为什么你期待不同的行为?在发布的代码中,我没有看到您在错误消息的{0}子字符串上明确执行令牌替换的位置。

我通常会做以下事情:

String messageBody = stringBuffer.toString().replaceAll("\\{0\\}", firstName);

或者您的字符串可以使用正确的字符串标记替换语法,以便在String的格式方法中使用:

String.format("%s: is Invalid.", "token");