Search code examples
javajsfjakarta-eejsf-2richfaces

JSF 2.1 conditional field validation


I have the following JSF 2.1 page

<h:selectOneRadio value="#{userBean.newUser}">
    <f:selectItem itemValue="0" itemLabel="new User" />
    <f:selectItem itemValue="1" itemLabel="existing User" />
</h:selectOneRadio>
<br />
<h:inputText value="#{userBean.customerId}" id="customerId" />
<h:message for="customerid" />
<br />
<h:inputText value="#{userBean.firstName}" id="firstName" />
<h:message for="fisrtName" />
<br />
<h:inputText value="#{userBean.lastName}" id="lastName" />
<h:message for="lastName" />
<br />
<h:commandButton value="Submit" action="#{userBean.login}" />

and this is my bean:

public class UserBean {

    private String customerId;
    private String newUser= "0";
    private String firstName;
    private String lastName;

    // Getters and seeters ommited.
}

I need to validate this form in the following way:

If the "new User" radio button selected, all form inputs should be validated. If "existing User" is selected I need to validate only the Customer Id.

I tried Hibernate Validation and I also tried a custom validator by implementing javax.faces.validator.Validator interface.

Can I achieve such functionality somehow?


Solution

  • You can write a custom validator which examines the parent UI component and performs validations only under certain conditions. It's quite complex. Maybe look at ExtVal and its @SkipValidation annotation?

    @SkipValidation("#{person.role eq 'admin'}")
    @Required
    @Equals("person.password")
    @NotEquals("password")
    private String oldPassword;