HTML and CSS Reference
In-Depth Information
Validator Interface
The
javax.faces.validator.Validator
interface is the core interface for the JSF validators. The JSF
Validator
interface describes a Java class that can perform validation (checks on the correctness) on
EditableValueHolder
components. A single
EditableValueHolder
can have zero or more validators in the view. Listing 3-10 shows the JSF
Validator
interface.
Listing 3-10.
JSF Validator Interface
package javax.faces.validator;
import java.util.EventListener;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
public interface Validator extends EventListener {
//...
public void validate(FacesContext context, UIComponent component, Object value) throws
ValidatorException;
}
As shown in the
Validator
interface, it contains a single API. The
validate
API performs the required validation
on the parent
EditableValueHolder
component's value; this API can be called in the
Process Validations phase
(or in
Apply Request Values phase
if
immediate
attribute of the
EditableValueHolder
is set to
true
).
validate()
API
has three parameters:
1.
context
, which represents the JSF
FacesContext
instance of this request.
2.
component
, which represents the component whose value will be validated.
This component instance can be used in order to retrieve the component attributes
if the validator needs to use them.
3.
value
, which represents the
String
value to be validated.
For every component that has a validator (or more). If the validation fails, the validator must throw
ValidatorException
; in this case, the component that owns the validator will be marked as invalid, and a
ValidatorException
message will be received and added to the
FacesContext
messages in order to be displayed
by the
<h:message>
component associated with the
EditableValueHolder
component and by the
<h:messages>
component.
Listing 3-11 shows an example to illustrate how validation works for multiple
EditableValueHolder
components
with attached validators. Notice that in this example,
number1
and
number2
are attributes in
TestBean
managed bean
and are of type
Long
.
Listing 3-11.
Validation Example for Multiple EditableValueHolder Components
<h:form>
<h:outputText value="Enter Number1: "/>
<h:inputText id="number1"
value="#{testBean.number1}">
<f:validateRequired/>
<f:validateLongRange minimum="0" maximum="999"/>
</h:inputText>
<h:message for="number1"/>