Bean Validation 2.0

DZone 's Guide to

Bean Validation 2.0

This dip into Bean Validation 2.0 covers the new annotations available, the enhanced support the API offers, and tips for validation.

· Java Zone ·
Free Resource

Bean Validation Constraint Challenge

The Bean Validation 2.0 API introduces new constraints. Quiz time: Which of the following are among those new constraints?


The new constraints are @NotBlank, @Email, @NegativeOrZero, and @PastOrPresent.

Bean Validation 2.0

Bean Validation 2.0 includes a range of new features. Among them are constraints that validate email addresses, ensure that numbers are positive or negative, test if dates are past or present, and test that fields are not empty or null. These are @Email, @Positive, @PositiveOrZero, @Negative, @NegativeOrZero, @PastOrPresent, @FutureOrPresent, @NotEmpty, and @NotBlank.

How to Use These Constraints

Constraints act in a wider range of locations than in previous API releases. They can proceed arguments of parameterized types, and support for validating container elements by type arguments has been added — as in the following code snippet.

List<@Size(min = 30) String> favourites;

Other Bean Validation Enhancements

Cascaded Validation of Containers

Cascaded validation of containers has been added. If you annotate any type argument of a container with @Valid, it will cause the validation of every element in that container when the parent object is validated. In the code snippet below, every Driver and Car element will be validated as shown:

Map<@Valid Driver, @Valid Car> driverAndCar;

Custom Container Types

Bean validation also adds support for custom container types by plugging in value extractors. Built-in constraints are marked as repeatable, parameter names are retrieved using reflection, and ConstraintValidator#initialize() is a default method. JavaFX also gets support for its types.

Java SE 8 Uplift

The API gets an uplift to Java SE 8’s Date and Time types and offers support for java.util.Optional.

Further Reading

For further information on how to use Bean Validation’s new features, please take consider my new book Java EE 8: Only What's New. Includes all new and updated APIs with working code examples: JSON Binding 1.0, Security 1.0, Servlet 4.0, Bean Validation 2.0, CDI 2.0, JAX-RS 2.1, JSF 2.3 and JSON Processing 1.1. You should also read the specifications for the Bean Validation 2.0 (JSR 380).

GitHub Repository

The code from this and all other #100DaysOfJavaEE8 can be found in my GitHub repository.

java ,java ee ,bean validation 2.0 ,java containers ,tutorial

Published at DZone with permission of Alex Theedom , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}