When standard validators don't satisfy your application needs, you need to write a custom validator. As per example, in this recipe you will see how to validate an IP address, an e-mail address, and a zip code. Following this strategy, you can write custom validators for phone numbers, credit card numbers, fax numbers, and so on.
We developed this recipe with NetBeans 6.8, JSF 2.0, and GlassFish v3. The JSF 2.0 classes were obtained from the NetBeans JSF 2.0 bundled library.
Writing custom validators is a straightforward process that starts with the task of creating a class that implements the javax.faces.validator.Validator
interface and the validate
method.
For JSF 1.2, register your custom validator in the faces-confix.xml
file. For JSF 2.0 use the javax.faces.validator.FacesValidator
annotation.
After we have written the validator class, we call it from JSF pages through the <f:validator/>
tag.
As per example, we have developed a custom validator to validate an IP address as shown next:
import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; @FacesValidator(value = "ipValidator") public class IpValidator implements Validator { private static final String IP_REGEX = "^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"; public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { String ipAddress = (String) value; Pattern mask = null; mask = Pattern.compile(IP_REGEX); Matcher matcher = mask.matcher(ipAddress); if (!matcher.matches()) { FacesMessage message = new FacesMessage(); message.setDetail("IP not valid"); message.setSummary("IP not valid"); message.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(message); } } }
And we have called this custom validator like this:
<h:inputText id="ipID" required="true" value="#{ipBean.ipValue}">
<f:validator validatorId="ipValidator"/>
</h:inputText>
It works exactly like a standard validator, but this time the called validator is a custom one. Before populating the managed bean, the values are validated by the custom validator. If an error occurs while validating the values then the process returns an error message and re-displays the form.
Since regular expressions are often used in validators, here it is a short list of the most used:
^[\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Z]{2,4}$
.*, [A-Z][A-Z]
###-##-####: [0-9]{3}-[0-9]{2}-[0-9]{4}
[0-9]{4}-[0-9]{2}-[0-9]{2}