Search code examples
springvalidationhibernate-validator

Spring validate nested object with condition on parent


What I want to achieve might be a bit weird but sadly I cannot change that easily. I have a DTO that has a nested resource. The nested resource gets validated and the validation it gets differs based on an attribute of its parent.

class rootDto {

  @NotEmpty
  private String type;

  @Valid
  private AddressDto address;

  // Other attributes follow ...
}

Now AddressDto looks like the following:

class AddressDto {

  @NotEmpty(/* ONLY IF rootDto.type IS 'xxx' */)
  private String name;

  @NotEmpty(/* ONLY IF rootDto.type IS 'yyy' */)
  private String street;

  // Other attributes follow ...
}

I read about class level contrains (example answer) but I don't think that this is what I want. I could always create a Validator for the rootDto and inside that have the conditional validations for the AddressDto but that would be ugly and will grow way too much since AddressDto is not the only nested resource I have that requires such validation.

So my main question is, can I somehow expose to the nested resource attributes from its parent in order to use them for the validation? Is there an alternative I have not found/thought?


Solution

  • If you are using Hibernate Validator as Bean Validation provider and are happy to use a non standard feature, you can use Hibernate Validator's GroupSequenceProvider SPI - http://docs.jboss.org/hibernate/validator/5.2/reference/en-US/html_single/#__literal_groupsequenceprovider_literal

    The idea would be to work with validation groups which you programmatically activate by using a GroupSequenceProvider on your RootDto.