Java Reference
In-Depth Information
label = htmlInputText.getLabel();
if (!matcher.matches()) {
FacesMessage facesMessage =
new FacesMessage(label +
": not a valid email address");
throw new ValidatorException(facesMessage);
In our example, the validate() method does a regular expression match against the
value of the JSF component we are validating. If the value matches the expression,
validation succeeds; otherwise, validation fails and an instance of javax.faces.
validator.ValidatorException is thrown.
The primary purpose of our custom validator is to illustrate how to
write custom JSF validations, and not to create a foolproof e-mail
address validator. There may be valid e-mail addresses that don't
validate using our validator.
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 neither 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 e-mail field to use our custom validator
using the following code:
<h:inputText id="email" label="Email Address"
required="true" value="#{}">
<f:validator validatorId="emailValidator"/>
Search WWH ::

Custom Search