javaspringhibernatehibernate-validator

How to access instance variables when interpolating message in Hibernate Validator?


I am using Hibernate Validator with Spring to validate object when inserting it into repository with CrudRepository::save. Let's say we have class:

public class Person {
  public int id;

  @NotBlank(message="User with id: ${id} is missing name")
  public String name;

}

I want the interpolated message to access all fields of the Person instance e.g. id field and then access them like "${id}" or "${this.id}". Documentation mentions something about being able to access all bean properties but I guess it can only be used with class-level constraints.

Is there some way to do this without resorting to using class-level constraints?


Solution

  • A constraint validator cannot access any info outside the field itself. So, in other words, there's no way to access sibling fields. This is related to the scope of a constraint. Look at it this way:

    @NotBlank
    public String name;
    

    A not blank name can be a field in person, or it can be a field in the company, or some other class. It makes no difference to @NotBlank where it is located.

    Hence as you've suggested in your question, to get access to other class fields when interpolating the message the constraint should be at a class level... To not create a lot of custom constraints, you might consider looking at a @ScriptAssert.

    Also note that ConstraintViolationException contains a list of ConstraintViolation in it and from it you should be able to get access to a leaf bean (getLeafBean()) or to root bean (getRootBean()), and get the info you need after the exception was thrown.