Spring 根据父级条件验证嵌套对象
Spring validate nested object with condition on parent
我想要实现的可能有点奇怪,但遗憾的是我不能轻易改变。我有一个具有嵌套资源的 DTO。嵌套资源得到验证,并且它获得的验证根据其父项的属性而有所不同。
class rootDto {
@NotEmpty
private String type;
@Valid
private AddressDto address;
// Other attributes follow ...
}
现在 AddressDto 如下所示:
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 ...
}
我读到了 class 级别限制 (example answer),但我认为这不是我想要的。我总是可以为 rootDto
创建一个 Validator
并在其中对 AddressDto
进行条件验证,但这会很丑陋并且会增长太多,因为 AddressDto
不是我拥有的唯一需要此类验证的嵌套资源。
所以我的主要问题是,我能否以某种方式公开其父级的嵌套资源属性以便将它们用于验证?有没有我没有的替代方案found/thought?
如果您使用 Hibernate Validator 作为 Bean Validation 提供程序并且乐于使用非标准功能,您可以使用 Hibernate Validator 的 GroupSequenceProvider
SPI - http://docs.jboss.org/hibernate/validator/5.2/reference/en-US/html_single/#__literal_groupsequenceprovider_literal
我们的想法是使用您通过在 RootDto
上使用 GroupSequenceProvider
以编程方式激活的验证组。
我想要实现的可能有点奇怪,但遗憾的是我不能轻易改变。我有一个具有嵌套资源的 DTO。嵌套资源得到验证,并且它获得的验证根据其父项的属性而有所不同。
class rootDto {
@NotEmpty
private String type;
@Valid
private AddressDto address;
// Other attributes follow ...
}
现在 AddressDto 如下所示:
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 ...
}
我读到了 class 级别限制 (example answer),但我认为这不是我想要的。我总是可以为 rootDto
创建一个 Validator
并在其中对 AddressDto
进行条件验证,但这会很丑陋并且会增长太多,因为 AddressDto
不是我拥有的唯一需要此类验证的嵌套资源。
所以我的主要问题是,我能否以某种方式公开其父级的嵌套资源属性以便将它们用于验证?有没有我没有的替代方案found/thought?
如果您使用 Hibernate Validator 作为 Bean Validation 提供程序并且乐于使用非标准功能,您可以使用 Hibernate Validator 的 GroupSequenceProvider
SPI - http://docs.jboss.org/hibernate/validator/5.2/reference/en-US/html_single/#__literal_groupsequenceprovider_literal
我们的想法是使用您通过在 RootDto
上使用 GroupSequenceProvider
以编程方式激活的验证组。