Observe the Following Code. A DealerLot has a carInventory, which consists of cars, all of which contain an engine. The current dealerlot has two cars in inventory, and when validated one of the car's engines fails validation. However the error message only contains information about the engine. What would be the cleanest way of including the carName in the message as well?
public class main {
@Data
@AllArgsConstructor
static class Engine {
@Pattern(regexp="V.*", message="Engine Name must start with a V! You provided ${validatedValue}")
private String engineName;
}
@Data
@AllArgsConstructor
static class Car {
private String carName;
@Valid
private Engine engine;
}
@Data
@AllArgsConstructor
static class DealerLot {
@Valid
private List<Car> carInventory;
}
public static void main(String args[]){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Engine engine1 = new Engine("VQ35DE");
Car car1 = new Car("Nissan 350z", engine1);
Engine engine2 = new Engine("2JZ-GTE");
Car car2 = new Car("Toyota Supra", engine2);
DealerLot dealerLot1 = new DealerLot(Arrays.asList(car1, car2));
Set<ConstraintViolation<DealerLot>> i = validator.validate(dealerLot1);
for (ConstraintViolation<DealerLot> v : i) {
System.out.println(v.getMessage());
};
}}
Output:
Engine Name must start with a V! You provided 2JZ-GTE
I would prefer output to look somewhat like the following:
Toyota Supra, Engine Name must start with a V! You provided 2JZ-GTE
Without this level of clarity it could be extremely confusing to determine which car(s) are having an issue.
FYI these are the version of the dependencies I am using in the example:
compile group: 'org.hibernate.validator', name: 'hibernate-validator', version: '6.0.17.Final'
compile group: 'org.glassfish', name: 'javax.el', version: '3.0.1-b11'
implementation group: 'org.projectlombok', name: 'lombok', version: "1.18.4"
compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'