Java Reference
In-Depth Information
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
public class EmailValidator implements Validator {
public void validate(FacesContext facesContext,
UIComponent uIComponent, Object value) t
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 {
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 email address val-
idator. There may be a valid email address that doesn't validate using
our validator.
Search WWH ::

Custom Search