Search code examples
jsfjsf-2convertersmessage

Customize converter message to include input with bolded invalid characters


Mojarra 2.1.29

Consider the standard javax.faces.Integer converter. If we enter an invalid number we'll recieve the message:

'foo' must be a number consisting of one or more digits

I need to customize the message as follows if the number contains invalid charaters, print the input along with bolded invalid charaters. For instance 1234add

The number contains invalid charaters: 1234add

I think it's not possible to just define my own custom properties file containing the message as follows:

javax.faces.converter.BigIntegerConverter.BIGINTEGER={2}: ''{0}'' must be a number consisting of one or more digits.

Do I have to write my own custom converter that is a subclass of the javax.faces.Integer?

Is it possible to customize the error-message in such a way without writing a custom converter?


Solution

  • Yes, it's possible. It's only hacky for two reasons:

    • Formatting logic is been encapsulated in EL instead of in a reusable Java class (although you could create a special tagfile to prevent copypasting over all place in case you intend to reuse same logic elsewhere).
    • HTML is needed in faces message while <h:message> doesn't support unescaping HTML (so a <h:outputText> which manually grabs the message is needed to display the message).

    Here it is:

    <h:inputText binding="#{input}"
        converter="javax.faces.Integer" 
        converterMessage="The number contains invalid charaters: #{input.submittedValue.replaceAll('(\\d*)?(\\D+)(\\d*)?', '$1&lt;b&gt;$2&lt;/b&gt;$3')}" />
    <h:outputText id="messageForInput" value="#{facesContext.getMessageList(input.clientId)[0].summary}" escape="false" />
    

    Note the importance of binding pointing to a local variable rather than a bean property.

    See also: