Showing label in custom validator
I created a new custom component implementing a custom validator. Here is how I call it in:
<p:inputText value="#{MyBean.value}" >
<f:attribute name="label" value="#{ResourceBean.labels['label']}"/>
<my:vali开发者_如何转开发dator error="#{ResourceBean.message['the.error.message']}"
expression="#{ResourceBean.regExp['alphanumeric']}"/>
</p:inputText>
And here is the validate implementation
String val = value == null ? "" : value.toString();
if (!val.matches(getExpression())) {
throw new ValidatorException(new
FacesMessage(FacesMessage.SEVERITY_ERROR,getErrorSummary(),null));
and the error message in property file:
the.error.message={0}\: is Invalid.
The problem is that the {0}
in not replaced by the label in the error message thus I am getting as error message:
{0}: is Invalid.
Any ideas how to fix it?
You need to use MessageFormat
API, like as JSF is doing under the covers.
String message = getErrorSummary();
String label = component.getAttributes().get("label");
String formattedMessage = MessageFormat.format(message, label);
throw new ValidatorException(new FacesException(formattedMessage));
Why are you expecting a different behavior? In the code posted I don't see where you are explicitly doing a token replace on the {0}
substring of your error message.
I usually do something like the following:
String messageBody = stringBuffer.toString().replaceAll("\\{0\\}", firstName);
Or your string can utilize proper syntax for string token replacement for use in String's format method:
String.format("%s: is Invalid.", "token");
精彩评论