Using a Custom Validator

The standard validators are sufficient for many applications, but sometimes you have to roll your own to get what you need. The filtering criteria form in the sample application, for instance, has two date fields for specifying a date range. With a custom validator, we can make sure that the date entered in the To field is in fact later than the date entered in the From field, so let’s build one. Figure 7-2 shows the filtering criteria form with a validation message from the custom validator.

The filtering criteria form with a custom validator
Figure 7-2. The filtering criteria form with a custom validator

Example 7-3 shows a custom validator class that compares the date values of two components to ensure that one is later than the other.

Example 7-3. The LaterThanValidator class
package com.mycompany.jsf.validator; import java.text.MessageFormat; import java.io.Serializable; import java.util.Date; import java.util.Locale; import java.util.ResourceBundle; import javax.faces.application.Application; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.EditableValueHolder; import javax.faces.component.ValueHolder; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; public class LaterThanValidator implements Validator, Serializable { private ...

Get JavaServer Faces now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.