O'Reilly logo

JavaServer Faces by Hans Bergsten

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required