Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying custom error message for a blank field in a simple JSF application

Tags:

jsf

message

I was trying out a simple JSF application, in which I need to check if the "name" field is blank, then display an error message.

The code which takes the field's value is:

<h:outputLabel value="Name"/>
<h:inputText value="#{greeting.name}" required="true">
    <f:validator validatorId="NumValidator"/>
</h:inputText>

The control of the program does not go into the validator class, if the field is submitted without entering anything, and it displays the default error message:

j_id_jsp_869892673_1:j_id_jsp_869892673_4: Validation Error: Value is required.

How do i display a custom message for this ?

like image 840
bibek Avatar asked Mar 25 '10 09:03

bibek


2 Answers

The Message.properties file stored the default validation messages. This file is contained in the JAR of the JSF implementation library.

If you look at the content of this file, regarding the required validation, you will see that:

javax.faces.component.UIInput.REQUIRED={0}: Validation Error: Value is required.

To define your own error messages, create a new properties file, add the adequate error message, for example:

javax.faces.component.UIInput.REQUIRED=Hey, you forgot to fill the input {0}!

(note that {0} will be replaced by the ID of the field)

then, in your faces-config.xml, define a new message-bundle:

<message-bundle>package.that.contains.the.properties.file</message-bundle>

So for example, if your my-messages.properties is stored in the foo/bar package, you will have to write:

<application>
  ...
  <message-bundle>foo.bar.my-messages</message-bundle>
</application>

(note that you will not have to specify the .properties extension)

like image 131
Romain Linsolas Avatar answered Sep 30 '22 18:09

Romain Linsolas


The way suggested by romaintaz is definitely way to go. On the other hand if you are looking for more customization, you can use a phase listener that fires before render response phase as does some customizing.

For example first define the value for key as below:

javax.faces.component.UIInput.REQUIRED=INPUT_REQ_FAIL

then for input components that require validation have them pass a attribute using f:attribute .Then in phase listener iterate over the face messages and check for INPUT_REQ_FAIL and replace it with cutom message along with the attribute value for the component.

like image 28
Inv3r53 Avatar answered Sep 30 '22 16:09

Inv3r53