10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

According to this validator, the data entered in the field must be one of the following:<br />

■ A 16 digit number with no spaces<br />

■ A 16 digit number with a space between every four digits<br />

■ A 16 digit number with hyphens between every four digits<br />

<strong>The</strong> rest of this section describes how this validator is implemented and how to create a custom<br />

tag so that the page author can register the validator on a component.<br />

Implementing theValidator Interface<br />

A Validator implementation must contain a constructor, a set of accessor methods for any<br />

attributes on the tag, and a validate method, which overrides the validate method of the<br />

Validator interface.<br />

<strong>The</strong> FormatValidator class also defines accessor methods for setting the formatPatterns<br />

attribute, which specifies the acceptable format patterns for input into the fields. In addition, the<br />

class overrides the validate method of the Validator interface. This method validates the<br />

input and also accesses the custom error messages to be displayed when the String is invalid.<br />

<strong>The</strong> validate method performs the actual validation of the data. It takes the FacesContext<br />

instance, the component whose data needs to be validated, and the value that needs to be<br />

validated. A validator can validate only data of a component that implements<br />

EditableValueHolder.<br />

Here is the validate method from FormatValidator:<br />

public void validate(FacesContext context, UIComponent component, Object toValidate) {<br />

boolean valid = false;<br />

String value = null;<br />

if ((context == null) || (component == null)) {<br />

throw new NullPointerException();<br />

}<br />

if (!(component instanceof UIInput)) {<br />

return;<br />

}<br />

if ( null == formatPatternsList || null == toValidate) {<br />

return;<br />

}<br />

value = toValidate.toString();<br />

//validate the value against the list of valid patterns.<br />

Iterator patternIt = formatPatternsList.iterator();<br />

while (patternIt.hasNext()) {<br />

valid = isFormatValid(<br />

((String)patternIt.next()), value);<br />

Creating a CustomValidator<br />

Chapter 12 • Developing with <strong>Java</strong>Server FacesTechnology 397

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!