Sunday, September 21, 2008

Validating a required checkbox in JSF and Faces

The required attribute of an <h:selectBooleanCheckbox> of Jakarta Faces (formerly known as JSF) is a bit non-intuitive. If you want to require the user to check the desired checkbox, you would assume that setting the required attribute to true ought to be sufficient:

<h:selectBooleanCheckbox id="agree" value="#{bean.agree}" required="true" requiredMessage="You must agree!" />

But it is not. As for every other UIInput component, the required="true" validation only checks if the value is actually filled and sent to the server side, i.e. the value is not null nor empty. In case of an <h:selectBooleanCheckbox>, which accepts Boolean or boolean properties only, an unchecked checkbox becomes Boolean.FALSE right before the validations phase. This value is not null nor empty! Thus, the required attribute of the <h:selectBooleanCheckbox> is fairly pointless. It always passes the validation, and thus never displays the desired required message in case of an unchecked checkbox. This is still so in Faces 4.1, on both Mojarra 4.1.21 (WildFly 42) and MyFaces 4.1.4 (Tomcat 11), where all examples below were tested.

RequiredCheckboxValidator

The best what you can do is to create your own Validator implementation specific for an <h:selectBooleanCheckbox> of which a checked value is required. It is relatively simple, just check if the value is not Boolean.TRUE and handle accordingly:

import jakarta.faces.application.FacesMessage;
import jakarta.faces.component.UIComponent;
import jakarta.faces.component.UIInput;
import jakarta.faces.context.FacesContext;
import jakarta.faces.validator.FacesValidator;
import jakarta.faces.validator.Validator;
import jakarta.faces.validator.ValidatorException;

@FacesValidator("requiredCheckboxValidator")
public class RequiredCheckboxValidator implements Validator<Boolean> {

    @Override
    public void validate(FacesContext context, UIComponent component, Boolean value) {
        if (!Boolean.TRUE.equals(value)) {
            String requiredMessage = ((UIInput) component).getRequiredMessage();
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, requiredMessage, null));
        }
    }
}

Note that this validator uses the requiredMessage attribute of the component as message. The @FacesValidator registers it by its validator ID, so there's no need for a <validator> entry in faces-config.xml. That's it! Attach this validator to the <h:selectBooleanCheckbox> using <f:validator>.

Basic demonstration example

Here is a sample form. It represents a kind of an agreement form which requires the checkbox being checked before submit. This is not an uncommon functional requirement.

<h:form>
    <h:outputLabel for="agree" value="Do you agree with me?" />
    <h:selectBooleanCheckbox id="agree" value="#{bean.agree}" requiredMessage="You must agree!">
        <f:validator validatorId="requiredCheckboxValidator" />
    </h:selectBooleanCheckbox>
    <h:commandButton value="Submit" action="#{bean.submit}" />
    <h:messages />
</h:form>
@Named
@RequestScoped
public class Bean {

    private Boolean agree;

    public void submit() {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You agreed with me!"));
    }

    public Boolean getAgree() {
        return agree;
    }

    public void setAgree(Boolean agree) {
        this.agree = agree;
    }
}

Now, when you submit the form with a checked checkbox, Faces just proceeds with the form processing, and shows "You agreed with me!". Otherwise it displays the desired required message "You must agree!".

OmniFaces

You don't need to write the validator yourself when you use OmniFaces. It has exactly this RequiredCheckboxValidator, by validator ID omnifaces.RequiredCheckboxValidator, and since OmniFaces 4.5 also as a tag:

<h:selectBooleanCheckbox id="agree" value="#{bean.agree}" requiredMessage="You must agree!">
    <o:requiredCheckboxValidator />
</h:selectBooleanCheckbox>

Without the requiredMessage, it shows a default message, e.g. "f:agree: a tick is required".

Bean Validation

When you already use Bean Validation, then @AssertTrue on the property does the same:

@AssertTrue(message = "You must agree!")
private Boolean agree;

An unchecked checkbox then shows "You must agree!" on Mojarra, and "f:agree: You must agree!" on MyFaces.

JSF 2.x

On JSF 2.x, use the javax.faces.* packages and the http://xmlns.jcp.org/jsf/* namespaces, or http://java.sun.com/jsf/* on JSF 2.0 and 2.1. The Validator interface is generic since JSF 2.3. Before that, implement the raw Validator, with Object value in the validate() method. The omnifaces.RequiredCheckboxValidator exists since OmniFaces 1.0, with the namespace xmlns:o="http://omnifaces.org/ui". On JSF 1.x, which has no @FacesValidator, register the validator in faces-config.xml:

<validator>
    <validator-id>requiredCheckboxValidator</validator-id>
    <validator-class>com.example.RequiredCheckboxValidator</validator-class>
</validator>