Java Reference
In-Depth Information
The constructor of
ValidatorException
takes an instance of
javax.faces.
application.FacesMessage
as a parameter. This object is used to display the error
message on the page when validation fails. The message to display is passed as a
String
to the constructor of
FacesMessage
. In our example, if the
label
attribute
of the component is not
null
nor empty, we use it as part of the error message,
otherwise we use the value of the component's
id
attribute. This behavior follows
the pattern established by standard JSF validators.
Our validator needs to be annotated with the
@FacesValidator
annotation. The
value of its
value
attribute is the ID that will be used to reference our validator in
our JSF pages.
Once we are done implementing our validator, we are ready to use it in our pages.
In our particular case, we need to modify the email field to use our custom validator.
<h:inputText id="email" label="Email Address"
required="true" value="#{registrationBean.email}">
<f:validator validatorId="emailValidator"/>
</h:inputText>
All we need to do is nest a
<f:validator>
tag inside the input field we wish to have
validated using our custom validator. The value of the
validatorId
attribute of
<f:validator>
must match the value of the value attribute in the
@FacesValidator
annotation in our validator.
At this point we are ready to test our custom validator.