Search code examples
javavalidationhibernate-validator

Java Validation: Validate an object within an object


I have two objects:

public class CancelRequest{
 @NotEmpty
 private String id;

 @NotNull
 private BookingDetails;
}

BookingDetails object:

public class BookingDetails{
 @NotEmpty
 private String bookingId;
}

My class that is responsible for validating the request is CancelRequestValidator

...
import javax.validation.Validator;
...
public class CancelRequestValidator{
...
public void check(CancelRequest request){
 Set<ConstraintViolation<NorthAmericaCancelTripRequest>> violations = 
validator.validate(request);
...
 }
}

how I am performing validation?

CancelRequest request = new CancelRequest("id",new BookingDetails(""));
CancelValidator validator = new CancelValidator();
violations = validator.check(request);

The violation should have one entry in it saying bookingId cannot be empty but instead it thinks that the object valid. I need to do the validation this way because I have some other business validation that I need to perform on this object hence I am using a mixture of javax and custom validation.

thanks


Solution

  • To perform nested bean validation, you need to use the @Valid annotation on the nested object:

    public class CancelRequest{
      @NotEmpty
      private String id;
    
      @NotNull
      @Valid
      private BookingDetails;
    }