background image

Value-Change Event Handler

<< Action Event Handler | The ValueChangeListener >>
<< Action Event Handler | The ValueChangeListener >>

Value-Change Event Handler

A backing bean method that performs validation must accept a FacesContext, the component
whose data must be validated, and the data to be validated, just as the validate method of the
Validator
interface does. A component refers to the backing bean method by using its
validator
attribute. Only values of UIInput components or values of components that extend
UIInput
can be validated.
Here is the backing bean method of CheckoutFormBean from the Coffee Break example:
public void validateEmail(FacesContext context,
UIComponent toValidate, Object value) {
String message =
"";
String email = (String) value;
if (email.contains(
'@')) {
((UIInput)toValidate).setValid(false);
message = CoffeeBreakBean.loadErrorMessage(context,
CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,
"EMailError");
context.addMessage(toValidate.getClientId(context),
new FacesMessage(message));
}
}
The validateEmail method first gets the local value of the component. It then checks whether
the @ character is contained in the value. If it isn't, the method sets the component's valid
property to false. The method then loads the error message and queues it onto the
FacesContext
instance, associating the message with the component ID.
See
"Referencing a Method That Performs Validation" on page 372
for information on how a
component tag references this method.
Writing a Method to Handle a Value-Change Event
A backing bean that handles a value-change event must be a public method that accepts a
value-change event and returns void. This method is referenced using the component's
valueChangeListener
attribute.
The Duke's Bookstore application does not have any backing bean methods that handle
value-change events. It does have a ValueChangeListener implementation, as explained in the
"Implementing Value-Change Listeners" on page 396
section.
For illustration, this section explains how to write a backing bean method that can replace the
ValueChangeListener
implementation.
As explained in
"Registering a Value-Change Listener on a Component" on page 359
, the name
component of the bookcashier.jsp page has a ValueChangeListener instance registered on it.
Writing Backing Bean Methods
Chapter 12 · Developing with JavaServer Faces Technology
407