5/06/2013

Validating Checkboxes in Primefaces

Validation is a good thing if you are going to make the data your get more robust. Almost all gui elements can be validated using the "required" attribute but not checkboxes. The problem is that JSF "translates" a non-checked checkbox to Boolean.FALSE which still fullfils the "required" requirements. The solution is rather easy: 

Write a validator that you´ll bind just to this one component and check for the Boolean.FALSE value yourself:


public class CheckboxValidator implements Validator {

 public void validate(FacesContext context, UIComponent component, Object value)

 throws ValidatorException {

   if (value.equals(Boolean.FALSE)) {
     throw new ValidatorException( new FacesMessage(FacesMessage.SEVERITY_ERROR, "message" "message"));

   }

 }

If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.