Search code examples
springvalidationinterpolation

Use another object field value in spring message interpolation


I am trying, if it's possible, to customize a message of a constraint with a value that is not actually the one that is being validated but belong to the same class.

public Car {
  @NotEmpty(message = The car of the model '${this.model}' requires a plate_number)
  String plate_number;

  String model;
}

And now after creating a new instance of it

Car myCar = new Car(null, Audi);

and having validated, I want to get the message "The car of the model Audi requires a plate_number"

I do not know if its possible. Thanks :)


Solution

  • I dont know about @NotEmpty annotation because your are creating a Car object using constructor and I also know when using javax or jakarta validation usually it is on DTO exposed into REST endpoints.

    As a alternative you can using Assert.notNull into contructor:

    public class Car {
    
      private String model;
    
      private String plate_number;
    
    
      public Car(String model, String plate_number) {
        this.model = model;
        Assert.notNull(plate_number,
            "The car of the model " + this.model + " requires a plate_number");
        this.plate_number = plate_number;
      }
    }
    

    And now when you will pass:

    Car car = new Car("Audi", null);
    

    In console you will have next one error message:

    java.lang.IllegalArgumentException: The car of the model Audi  requires a plate_number