Search code examples
validationjsfbean-validationhibernate-validator

Form validation in JSF


I'm trying to validate a form before submitting, but is not working as expected.

Here my XHTML

<h:outputLabel for="name">Name: </h:outputLabel>
<p:inputText id="name"  value="#{partyCreationBean.name}" />
<h:message for="name"/>
<h:outputLabel for="symbol">Symbol: </h:outputLabel>

Here my webBean:

@ManagedBean(name = "partyCreationBean")
@RequestScoped
public class PartyCreationBean {

    @EJB
    PartyManagerLocal ejb_partymanager;
    @EJB
    AuthenticationManagerLocal ejb_user;

    private PartyDTO party = new PartyDTO();

    public String getName() {
        return party.getName();
    }

    public void setName(String name) {
        party.setName(name);
}

Here my DTO:

import org.hibernate.validator.constraints.*;

public class PartyDTO implements IDataTransferObject {
    private Integer id;
    @NotEmpty()
    private String name;

    //Getters, setters and other stuff.
}

Now the point is that if I leave "Name" empty and I press the button to create my party, the page just remain all the sames, and i get Exceptions in the console stack traces (a lot like usual :D )

I tried to work with this XHTML (adding require="true"):

<h:outputLabel for="name">Name: </h:outputLabel>
<p:inputText id="name" required="true" value="#{partyCreationBean.name}" />
<h:message for="name"/>
<h:outputLabel for="symbol">Symbol: </h:outputLabel>

and it is working well but I want to put my "constraints" in the DTO level...

Thanks in advance :)


Solution

  • @NotEmpty will not work like that..

    You need to build getters and setters to this:

    private PartyDTO party = new PartyDTO();
    

    Then you need to create getters and setters to

    @NotEmpty
    String name; 
    

    Then in the xhtml file..

    <p:inputText id="name"  required="true" value="#{partyCreationBean.party.name}" />
    

    And it should work. Of course if you will use required it will be fine as is..

    This can also help you if you will have other issues.. Few jsf Paramters that need to be added sometimes: Bean Validation @NotNull, @NotBlank and @NotEmpty does not work in JSF+Tomcat