December 22, 2014
Hot Topics:

The First Time Ever I Saw Your Face: Getting Started with JavaServer Faces

  • March 31, 2008
  • By David Thurmond
  • Send Email »
  • More Articles »

Performing Forms Validation

The next step in the development process is to create the validation logic for the forms input the user will submit. There are four ways to perform validation in JSF:

  1. Validation using built-in JSF validators
  2. In-line validation
  3. Using a Validator class
  4. Creating a custom validator tag

Each approach has advantages for various situations. I'll explain each in detail in the following sections.

Built-In Validation

JSF provides built-in validator classes to check some simple validation criteria, such as whether required fields are present, or if a numeric value falls into a desired range of values. An example of this is the <h:inputText> tag for the player name on the newGame.jsp page:

<h:inputText id="playerName"
             value="#{GameBean.playerName}"
             size="25"
             required="true"/>

The required attribute tells JSF to use the predefined JSF validator to determine whether a field value for player name was entered. Validation occurs when the form containing this control is submitted. If the validation check fails, a message is displayed by using the <h:message> tag:

<h:message style="color: red;
           font-family: 'New Century Schoolbook', serif;
           font-style: oblique;
           text-decoration: overline" id="errors1"
                            for="playerName"/>

Note the "for" attribute on this tag. This attribute specifies that any validation messages associated with the UI component whose ID is "playerName" should be displayed where this tag appears, using the specified style for the text. The error message that is displayed is the standard JSF validation message for required fields, but this can easily be overridden in the application's resource bundle to present a more user-friendly message.

If the validation check passes, JSF then determines which page should be displayed by using the navigation rules defined earlier, which, in this case, would send the user to the showPuzzle.jsp page.

Even though the predefined validators do provide some useful functionality, they are limited in what they can do. Next, you'll see how to add some additional complexity to application validation.

In-Line Validation

To provide more complicated validation logic for the application, you can implement an in-line validation method to check various conditions and give appropriate error messages. An example of this is shown on showPuzzle.jsp for the guessed letter input field:

<h:inputText id="guessLetter"
             value="#{GameBean.guessedLetter}"
             validator="#{GameBean.validate}"/>

The "validator" attribute on the tag indicates to JSF that the GameBean's validate() method should be invoked when the form's input needs to be checked.This method is shown below:

public void validate(FacesContext facesContext,
   UIComponent uIComponent, Object value)
   throws ValidatorException {
   String msg1 = getBundle().getString(GUESS_A_LETTER_MSG);
   String msg2 = getBundle().getString(LETTER_ALREADY_GUESSED_MSG);

   // Get the component's contents and cast it to a String
   String theLetter = value.toString().trim().toUpperCase();

   if (theLetter.length() == 0) {
      FacesMessage message = new FacesMessage();
      message.setDetail(msg1);
      message.setSummary(msg1);
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
   } // if

   String alreadyGuessedLetters = thePuzzle.getGuessedLetters();
   if (alreadyGuessedLetters.contains(theLetter)) {
      FacesMessage message = new FacesMessage();
      message.setDetail(msg2);
      message.setSummary(msg2);
      message.setSeverity(FacesMessage.SEVERITY_ERROR);
      throw new ValidatorException(message);
   } // if

} // validate()

The two checks that are performed in this message are to verify that a value was actually entered and to check whether the user already guessed that letter. If either of these conditions turns out to be true, a new FacesMessage with the appropriate internationalized error message is created, and a ValidationException is thrown. JSF then will recognize the fact that validation did not pass, and will display the generated message on the UI wherever the <h:message> tag is displayed:

<h:message for="guessLetter" />

Using a Validator Class

Although the in-line validation approach is more flexible than the built-in validators, it lacks reusability. If this same series of validation checks might be needed throughout the application, or across several applications, it would be best to create a validator class that could be reused independently of the application itself. An example of this might be a credit card number validator that checks the format of the credit card digits entered, and gives a validation exception if alphabetic characters appear in the number, or if the checksum for the number does not compute properly.





Page 6 of 8



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel