Java Reference
In-Depth Information
Chapter 22. Bean Validation: Advanced Topics
This chapter describes how to create custom constraints, custom validator messages, and
constraint groups using the Java API for JavaBeans Validation (Bean Validation).
The following topics are addressed here:
• “ Creating Custom Constraints ” on page 449
• “ Customizing Validator Messages on page 450
• “ Grouping Constraints on page 451
Creating Custom Constraints
Bean Validation defines annotations, interfaces, and classes to allow developers to create
custom constraints.
Using the Built-In Constraints to Make a New Constraint
Bean Validation includes several built-in constraints that can be combined to create new, re-
usable constraints. This can simplify constraint definition by allowing developers to define
a custom constraint made up of several built-in constraints that may then be applied to com-
ponent attributes with a single annotation.
Click here to view code image
@Pattern.List({
@Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_'{|}~-]+(?:\\."
+"[a-z0-9!#$%&'*+/=?^_'{|}~-]+)*"
+"@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-
z0-9-]*[a-z0-9])?")
})
@Constraint(validatedBy = {})
@Documented
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Email {
String message() default "{invalid.email}";
Class<?>[] groups() default {};
Search WWH ::




Custom Search