Chapter 2. Using Standard and Custom Validators in JSF

In this chapter, we will cover:

  • Using a standard validator
  • Customizing error messages for validators
  • Creating a custom validator
  • Binding validators to backing bean properties
  • Validating forms with RichFaces rich:beanValidator
  • Validating forms with RichFaces rich:ajaxValidator
  • Apache MyFaces Commons validators
  • Bean validation with f:validateBean
  • Enforcing a value's presence with f:validateRequired
  • Using regular expressions with f:validateRegex

Introduction

Validation ensures the application data contains the expected content. For example, we can validate the ranges of numbers or upper/lower limits, string lengths, date formats, and so on. Every time we need restrictions on a UIInput component or component whose classes extends UIInput we can use the validation mechanism. JSF provides four types of validation, as follows:

  • Standard validation components
  • Application-level validation
  • Custom validation components
  • Validation methods in backing beans

Validators are invoked during the Process Validations Phase of the JSF lifecycle. For example, if we assume a form that is submitted with a set of values, a validator for those values, a corresponding backing bean, and a render page, then the application lifecycle will be like this (notice when and where the validator is involved!):

  • Restore View Phase: The backing bean is created and the components are stored into the UIViewRoot
  • Apply Request Values Phase: The submitted values are decoded and set in the corresponding components in UIViewRoot
  • Process Validations Phase: The validator is called and the submitted values are checked for the desired restrictions
  • Update Model Values Phase: The validated values are set in the backing bean
  • Invoke Application Phase: This phase is responsible for form processing
  • Render Response Phase: The values that should be displayed are extracted from backing beans

Using the proper validator is the developer's choice. The developer is also responsible for customizing the error messages displayed when the validation fails. When the standard validators don't satisfy the application needs, the developer can write custom validators as you will see in our recipes.

Notice that our recipes make use of JSF 2.0 features, annotation, new navigation style, and no faces-config.xml file. Especially, you must notice the new JSF 2.0 validators described here.

But before that, let's start with a simple recipe about working with standard validators.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset