Reputation: 8732
I am using Hibernate Validator - 5.2.2 (JSR 303).
I am doing a cross field validation, so I need to create a custom validator.
However I have no idea how to do the custom conditional nested validation.
example:
@ValidChildrenIfEnabled
public class MainDto {
public boolean isEnabled;
public List<Child> children;
}
public class Child {
@NotBlank
public String name;
@Range(min = 1, max = 3)
public int age;
}
If I don't need conditional validation, I would put @Valid on top of "children".
@Valid
public List<Child> children;
Note: I know how to create a custom validator, I just don't know how to create a custom validator that do nested validation that take advantage of existing built-in validator. Thanks!
EDIT:
My payload actually has one more payload, let's say SuperDto.
public class SuperDto {
@Valid
public List<MainDto> mainDtos;
}
And I do validation like this:
validator.validate(superDto);
Upvotes: 1
Views: 149
Reputation: 10549
Interesting use case. Unfortunately, I don't think you can do what you want to do as you can't trigger a validation from isValid().
Supposing that you have other constraints you want to validate in every cases, I think the best workaround is probably to use groups. And to use different groups depending of if isEnabled is true or not.
Anyway, you would have to special case how this bean is validated.
Upvotes: 1