开发者

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

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:v开发者_StackOverflow中文版alidator 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 ?


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)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜