Java Reference
In-Depth Information
Of course, a negative age wouldn't make much sense. However, our application
validates that user input is a valid integer with essentially no effort on our part.
The e-mail address input field of our page is bound to a property of type string in our
named bean. There is no built-in validation to make sure that the user enters a valid
e-mail address. In cases like this, we need to write our own custom JSF validator.
Custom JSF validators must implement the javax.faces.validator.Validator
interface. This interface contains a single method named validate() , and
this method takes three parameters, an instance of javax.faces.context.
FacesContext , an instance of javax.faces.component.UIComponent containing
the JSF component we are validating, and an instance of java.lang.Object
containing the value entered by the user for the component. The following example
illustrates a typical custom validator:
package com.ensode.jsf.validators;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator(value ="emailValidator")
public class EmailValidator implements Validator {
public void validate(FacesContext facesContext,
UIComponent uiComponent, Object value) throws
ValidatorException {
Pattern pattern = Pattern.compile("\\w+@\\w+\\.\\w+");
Matcher matcher = pattern.matcher(
(CharSequence) value);
HtmlInputText htmlInputText =
(HtmlInputText) uiComponent;
String label;
if (htmlInputText.getLabel() == null ||
htmlInputText.getLabel().trim().equals("")) {
label = htmlInputText.getId();
} else {
Search WWH ::

Custom Search