7

I have a contact form and I have some fields that are validated by bean validation, how could I return bean validation error messages after submitting?

For example:

<h:form>
    <h:inputText id="name" value="#{contact.client.name}"></h:inputText>Name (Required)
    <h:inputText id="email" value="#{contact.client.email}"></h:inputText>E-Mail (Required)
    <h:inputText id="website" value="#{contact.client.website}"></h:inputText>Website (Optional)
    <h:inputText id="text" value="#{contact.client.text}"></h:inputText>Message (Required):

    <h:commandButton value="Send" action="#{contact.sendMessage}" >
        <f:ajax execute="@form" render="@form"/>
    </h:commandButton>

</h:form>

This is how I'm validating my fields:

        // Client.java (model)
    @NotNull(message="Please provide your name")
    private String name;

    @NotNull(message="Please provide your email")
    @Pattern(regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Invalid e-mail")
    private String email;

    @Pattern(regexp = "(http[s]?://|ftp://)?(www\\.)?[a-zA-Z0-9-\\.]+\\.([a-zA-Z]{2,5})$", message = "Not valid URL")
    private String website;

    @NotNull(message="Please provide your message")
    private String text;
Valter Silva
  • 16,446
  • 52
  • 137
  • 218

1 Answers1

11

Either use <h:message> which you attach to specific components by for attribute which should refer the id of the input component:

<h:inputText id="name" value="#{contact.client.name}"></h:inputText>Name (Required)
<h:message for="name" />
<h:inputText id="email" value="#{contact.client.email}"></h:inputText>E-Mail (Required)
<h:message for="email" />
<h:inputText id="website" value="#{contact.client.website}"></h:inputText>Website (Optional)
<h:message for="website" />
<h:inputText id="text" value="#{contact.client.text}"></h:inputText>Message (Required):
<h:message for="text" />

or use <h:messages/> to display them all at a single place:

<h:messages />

Yes, bean validation messages also ends in there.

Don't forget to ensure that the button's render attribute covers them as well.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • i follow your tutorial but i have a weird problem, i update my post, please coud you take a look ? – Valter Silva Aug 08 '11 at 18:09
  • Is the concrete problem solved? Your new problem is unrelated. It look more like just a CSS issue. – BalusC Aug 08 '11 at 18:13
  • yeah it is mate, thanks by the help. i will take a look in my CSS though. – Valter Silva Aug 08 '11 at 18:16
  • 1
    It mentions it in your tutorial but `javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL` needs to be set as a `context-param` in the `web.xml` for the `@NotNull` bean validator to work properly. Just for anyone wondering why your bean validation messages aren't appearing (like I was) – PDStat Jun 22 '16 at 10:36