Registering a Custom Validator
Okay, so now we have a custom validator
and all its messages are
defined in the custMessage.properties file. How
can we use it? In Java code, you could simply create an instance of
the validator class, set the peerId
property, and
attach the validator to a
component, like this:
import com.mycompany.jsf.validator.LaterThanValidator; import javax.faces.component.UIInput; UIInput from = new UIInput( ); from.setId("from"); UIInput to = new UIInput( ); LaterThanValidator validator = new LaterThanValidator( ); validator.setPeerId("from"); to.addValidator(validator); ...
But, as I mentioned earlier, JSF allows you to register pretty much
every type of class under a symbolic name, so that you can replace
implementations without changing all the code that uses it.
Validators are no exception, and here’s how you
register the LaterThanValidator
in the
faces-config.xml file:
<faces-config> ... <validator> <validator-id>com.mycompany.jsf.validator.LATER_THAN</validator-id> <validator-class> com.mycompany.jsf.validator.LaterThanValidator </validator-class> <property> <property-name>peerId</property-name> <property-class>java.lang.String</property-class> </property> </validator> ... </faces-config>
A top-level <validator>
element
contains a
<validator-id>
element with a unique
identifier and a <validator-class>
element
with the fully qualified class name. The
<property>
element, with nested
<property-name>
and
<property-class>
elements, declares a supported property. ...
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.