HTML and CSS Reference
In-Depth Information
If you are familiar with Java annotations, using the
@interface
, you can create an annotation type.
@Target
annotation indicates the Java program elements to which the annotation type is applicable (in this example, these
elements are Java fields and methods). Java Bean Validation specification (JSR 303) mandates that any constraint
annotation defines the following attributes:
1.
message
attribute, which should be by default returning an error message. It can return
either the actual error message text or the error message key by using the curly brackets as
follows
"{key}"
. In the previous code listing, it returns
email.invalid
key.
2.
groups
attribute, which allows specifying validation groups, to which this constraint
belongs.
3.
payload
attribute, which can be used by clients of the Java Bean Validation API to assign
custom payload objects to a constraint (outside of the scope of this topic).
@Constraint
annotation is a Java Bean Validation annotation which refers to the reference of the class that
performs the validation logic using
validatedBy
attribute. Listing 3-17 shows the
EmailValidator
validation class
implementation.
Listing 3-17.
EmailValidator Validation Class
package com.jsfprohtml5.subscriber.bean.validation.custom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class EmailValidator implements ConstraintValidator<EmailAddress, String> {
private static final String EMAIL_REGEX = "(.+@.+\\.[a-zA-Z]+)?";
private Pattern pattern;
private Matcher matcher;
@Override
public void initialize(EmailAddress constraintAnnotation) {
pattern = Pattern.compile(EMAIL_REGEX);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
matcher = pattern.matcher(value);
if (! matcher.matches()) {
return false;
}
return true;
}
}