How to customize JSF validation error message
Asked Answered
V

3

23

How can I customize the validation message that appears when validation fails?

Here is the code I have:

<h:form>
    <p><h:inputText
           id="userNo"
           title="Type a number from 0 to 10:">
       <f:validateLongRange
           minimum="3"
           maximum="6"/>
       </h:inputText>

       <h:commandButton id="submit" value="Submit"
           action="response"/>
    </p>
    <h:message showSummary="true" showDetail="false"
        id="errors1"
        for="userNo"/>
</h:form>

Currently the message looks like this:

j_idt10:userNo: Validation Error: Specified attribute is not between the expected values of 3 and 6. 

Which is not particularly user-friendly.

Vitrify answered 2/5, 2012 at 10:18 Comment(0)
P
46

The simplest way would be to set the validatorMessage="my custom message" attribute in the <h:inputText> tag.

For a more advanced way read this article Customize validation error message in JSF 2.0

And here a complete Reference to all available message that you can override in JSF 2.0.x

Phocine answered 2/5, 2012 at 10:23 Comment(3)
It is surprising to me that there is no way to set the message "on-the-fly" in an attribute or something. Huh...Vitrify
That definitely makes more sense. But what if I have more than one validator attached to the input and I want to customise the messages of each of them?Vitrify
then you need to override the default message for each validator (in the Messages.properties file) like in the article I postedPhocine
A
15

In addition to Daniel's answer you could always use the label attribute for your input components to remove the client-id (j_idt10:userNo:) from the error message.

E.g. with

<h:inputText id="userNo" title="Type a number from 0 to 10:"
             label="User number">
  <f:validateLongRange
           minimum="3"
           maximum="6"/>
</h:inputText>

will produce:

User number: Validation Error: Specified attribute is not between the expected values of 3 and 6.

The label attribute can be an el expression as well to change this part of the error message dynamically.

Abessive answered 2/5, 2012 at 10:42 Comment(0)
F
8

You can use validatorMessage property of input text. Use requiredMessage property for required message, it is different from validator message.

<h:input text required ="true" validatorMessage="Enter user friendly message">
    <f:validateLongRange
        minimum="3"
        maximum="6"/>
</h:inputText>
Fugacious answered 30/3, 2015 at 15:25 Comment(1)
Description addedCrypto

© 2022 - 2024 — McMap. All rights reserved.