HTML and CSS Reference
In-Depth Information
Listing 3-12. EmailValidator Class
package com.jsfprohtml5.example.validators;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("com.jsfprohtml5.EmailValidator")
public class EmailValidator implements Validator {
private static final String EMAIL_REGEX = "(.+@.+\\.[a-zA-Z]+)?";
private Pattern pattern;
private Matcher matcher;
public EmailValidator() {
pattern = Pattern.compile(EMAIL_REGEX);
}
@Override
public void validate(FacesContext context,
UIComponent component,
Object value)
throws ValidatorException {
matcher = pattern.matcher(value.toString());
if (! matcher.matches()) {
FacesMessage message = new FacesMessage("Invalid Email format",
"Use for example: xyz@company.com " );
message.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(message);
}
}
}
In the validate() method which is called in the Process Validations phase (or Apply Request Values phase ),
the validation occurs, and as shown in the bolded lines, if the input String does not meet the e-mail format, a
ValidatorException with a Faces error message is thrown. It is important to notice the @FacesValidator annotation,
which is used for registering the validator. The @FacesValidator annotation has one main attribute, the value()
attribute, which is taken to be the ID of the validator. For this example, we use the value() attribute and declared our
validator ID to be "com.jsfprohtml5.EmailValidator" .
Search WWH ::




Custom Search