Running your first Bean Validation 2.0 code
Bean Validation is a Java specification that basically helps you to protect your data. Through its API, you can validate fields and parameters, express constraints using annotations, and extend your customs' validation rules.
It can be used both with Java SE and Java EE.
In this recipe, you will have a glimpse of Bean Validation 2.0. It doesn't matter whether you are new to it or already using version 1.1; this content will help you get familiar with some of its new features.
Getting ready
First, you need to add the right Bean Validation dependency to your project, as follows:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> <scope>test</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.8.Final</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.el</artifactId> <version>3.0.1-b10</version> </dependency> </dependencies>
How to do it...
- First, we need to create an object with some fields to be validated:
public class User {
@NotBlank
private String name;
@Email
private String email;
@NotEmpty
private List<@PositiveOrZero Integer> profileId;
public User(String name, String email, List<Integer> profileId) {
this.name = name;
this.email = email;
this.profileId = profileId;
}
}
- Then we create a
test
class to validate those constraints:
public class UserTest { private static Validator validator; @BeforeClass public static void setUpClass() { validator = Validation.buildDefaultValidatorFactory() .getValidator(); } @Test public void validUser() { User user = new User( "elder", "[email protected]", asList(1,2)); Set<ConstraintViolation<User>> cv = validator .validate(user); assertTrue(cv.isEmpty()); } @Test public void invalidName() { User user = new User( "", "[email protected]", asList(1,2)); Set<ConstraintViolation<User>> cv = validator .validate(user); assertEquals(1, cv.size()); } @Test public void invalidEmail() { User user = new User( "elder", "elder-eldermoraes_com", asList(1,2)); Set<ConstraintViolation<User>> cv = validator .validate(user); assertEquals(1, cv.size()); } @Test public void invalidId() { User user = new User( "elder", "[email protected]", asList(-1,-2,1,2)); Set<ConstraintViolation<User>> cv = validator .validate(user); assertEquals(2, cv.size()); } }
How it works...
Our User
class uses three of the new constraints introduced by Bean Validation 2.0:
@NotBlank
: Assures that the value is not null, empty, or an empty string (it trims the value before evaluation, to make sure there aren't spaces).@Email
: Allows only a valid email format. Forget those crazy JavaScript functions!@NotEmpty
: Ensures that a list has at least one item.@PositiveOrZero
: Guarantees that a number is equal or greater than zero.
Then we create a test
class (using JUnit) to test our validations. It first instantiates Validator
:
@BeforeClass public static void setUpClass() { validator = Validation.buildDefaultValidatorFactory().getValidator(); }
Validator
is an API that validates beans according to the constraints defined for them.
Our first test
method tests a valid user, which is a User
object that has:
- Name not empty
- Valid email
profileId
list only with integers greater than zero:
User user = new User( "elder", "[email protected]", asList(1,2));
And finally, the validation:
Set<ConstraintViolation<User>> cv = validator.validate(user);
The validate()
method from Validator
returns a set of constraint violations found, if any, or an empty set if there are no violations at all.
So, for a valid user it should return an empty set:
assertTrue(cv.isEmpty());
And the other methods work with variations around this model:
invalidName()
: Uses an empty nameinvalidEmail()
: Uses a malformed emailinvalidId()
: Adds some negative numbers to the list
Note that the invalidId()
method adds two negative numbers to the list:
asList(-1,-2,1,2));
So, we expect two constraint violations:
assertEquals(2, cv.size());
In other words, Validator
checks not only the constraints violated, but how many times they are violated.
See also
- You can check the Bean Validation 2.0 specification at http://beanvalidation.org/2.0/spec/
- The full source code of this recipe is at https://github.com/eldermoraes/javaee8-cookbook/tree/master/chapter01/ch01-beanvalidation/