Writing your own validator is a straightforward process. It involves implementing the Validator API and making sure you register it properly.
Say you want to write a validator that will not allow you to use the string "Hello World" as a value.
package nohelloworld;
public class NoHelloWorldValidator implements Validator {
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException
if (value != null && "Hello World".equals(value.toString()) {
throw new ValidatorException(new FacesMessage("Hello World is invalid"));
}
}
}
To make sure you can use your custom Validator you will need configure it so the JSF runtime knows about it. Adding it to your faces-config.xml will do the trick.
<validator>
<validator-id>NoHelloWorldValidator</validator-id>
<validator-class>nohelloworld.NoHelloWorldValidator</validator-class>
</validator>
And hooking this validator up to a inputText would be done as follows.
<h:inputText value="#{echo.message}">
<f:validator validatorId="NoHelloWorldValidator"/>
</h:inputText>
Posted September 9, 2012