Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize JSF validation error message

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.

like image 713
Eleeist Avatar asked May 02 '12 10:05

Eleeist


3 Answers

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

like image 147
Daniel Avatar answered Oct 23 '22 09:10

Daniel


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.

like image 15
Matt Handy Avatar answered Oct 23 '22 08:10

Matt Handy


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>
like image 8
Arpita Nayak Avatar answered Oct 23 '22 07:10

Arpita Nayak