views:

622

answers:

2

Hi all, 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 ?

+7  A: 

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:

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

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

romaintaz
+1  A: 

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.hope it helps.

daedlus