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; 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.