Java Programming Tutorials

Java programming tutorials with many code examples!

Java Bean Validation example

In this post we show Java Bean Validation example! Bean Validation is fantastic and flexible library that can be used in JEE and JSE programs to verify data!

Bean Validation implementation

Because Bean Validation is only an API we need to add an actual implementation to our project (assuming we’re running a project in JSE, without any JEE server). As the implementation we’ll use Hibernate Validator – the reference implementation. Let’s add project dependencies to pom.xml:

<!-- this will provide also Bean Validator API: -->
<!-- Needed by HV to substitute prams in messages: -->

Business object to validate

To illustrate how to validate data using Bean Validator let’s create a very simple class with a few constraints:

package com.farenda.javax.validation;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;

public class Player {

    // name have to be 3 chars:
    @Size(min = 3, max = 3)
    private String name;

    // possible score in game:
    @Min(0) @Max(1000)
    private int score;

    public Player(String name, int score) { = name;
        this.score = score;

    // just for logs
    public String toString() {
        return "Player{name='" + name + '\'' + ", score=" + score + '}';

Bean validator

Instantiating validator

The first thing we have to do is to create ValidationFactory that will provide us an implementation of Validator. Then we can use it to perform validations of our beans and finally close the ValidatorFactory, which will close the factory and all it’s validators:

package com.farenda.javax.validation;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class RunValidator {

    public static void main(String[] args) {
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        Validator validator = vf.getValidator();

        validate(validator, new Player("ABC", 44));

        validate(validator, new Player("a", 0));


    private static void validate(Validator validator, Player player) {
        // see below...

Note: Implementations of ValidationFactory and Validator are thread-safe.

Bean Validation method

Having a Validator instance we can perform actual validation of the Player. The task is very simple – we just call validator.validate(player). This method returns non-null set of validation errors (NullObject Pattern). If it is empty then we know that the object is valid, else we can get details of each violated constraint and can throw ConstraintViolationException with the violations as the only argument:

private static void validate(Validator validator, Player player) {
    Set<ConstraintViolation<Player>> violations
        = validator.validate(player);
    if (violations.isEmpty()) {
        System.out.println("Valid player: " + player);
    } else {
        for (ConstraintViolation<Player> violation : violations) {
            System.out.println("Invalid player: "
                 + violation.getRootBean());
            System.out.println("Offending property: "
                 + violation.getPropertyPath());
            System.out.println("Offending value: "
                 + violation.getInvalidValue());
            System.out.println("Message: "
                 + violation.getMessage());
        throw new ConstraintViolationException(violations);

Results of validation

Here’s the output of running Bean Validation in the above program:

sty 17, 2017 10:40:39 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.2.4.Final
Valid player: Player{name='ABC', score=44}
Invalid player: Player{name='a', score=-1}
Offending property: name
Offending value: a
Message: size must be between 3 and 3
Invalid player: Player{name='a', score=-1}
Offending property: score
Offending value: -1
Message: must be greater than or equal to 0
Exception in thread "main" javax.validation.ConstraintViolationException
        at com.farenda.javax.validation.RunValidator.validate(
        at com.farenda.javax.validation.RunValidator.main(

As you can see all constraints were checked and collected – the second player violated name and score constraints.

Share with the World!