5
votes

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 ?

3
Note that when you actually would like to override that ugly-looking j_id_jsp_869892673_1:j_id_jsp_869892673_4, then you need to specify the label attribute of the UIInput element, e.g. <h:inputText label="Name">.BalusC
@BalusC: thanks. wanted to get rid of that ugly j_id_jsp_869892673_1:j_id_jsp_869892673_4bibek

3 Answers

21
votes

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)

2
votes

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.

-1
votes

I think you should look at JSR 303! This is fully standard based user input, it works out of the box with JSF 2 (I use My Faces). And the nice thing is, no need for xml or properties files to specify custom messages.