Java Reference
In-Depth Information
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 {
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
validator. There may be valid email addresses that don't validate using
our validator.
 
Search WWH ::




Custom Search