STheFox
STheFox

Reputation: 1498

Java Hibernate validation return invalid fields

I am working with Validation annotations from Java Hibernate in my projects. I want to validate the data that I receive and return an array of invalid fields. Is that possible?

Let's say I have a Java class named Car:

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    @CheckCase(CaseMode.UPPER)
    private String licensePlate;

    @Min(2)
    private int seatCount;

    public Car ( String manufacturer, String licencePlate, int seatCount ) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

Let's say I create a new Car:

Car c = new Car("AUDI", NULL, 1);

This should not be possible because the license plate should be filled in and the number of seats should be greater than or equal to 2. So I want to return an array of two elements saying that license plate and number of seats are invalid (with extra message if possible).

Upvotes: 0

Views: 95

Answers (1)

Naros
Naros

Reputation: 21143

As ElmerCat points out, your constructor should be defined as:

public Car (
  @NotNull String manufacturer,
  @NotNull @Size(min = 2, max = 14) @CheckCase(CaseMode.UPPER) String licensePlate,
  @Min(2) int seatCount) {
    this.manufacturer = manufacturer;
    this.licensePlate = licensePlate;
    this.seatCount = seatCount;
}

Upvotes: 1

Related Questions