I'm using hibernate validations
for validating incoming requests in spring @RestController
.
Problem: I want to reuse the same DTO
object in multiple endpoints. But validate some fields only by condition (eg only on specific endpoints).
@RestController
public class ProductsServlet {
@GetMapping("/avail/product")
public Object avail(@Valid ProductDTO product) {
//should validate id field only
}
@GetMapping("/sell/product")
public Object sell(@Valid(with = GroupFuture.class) ProductDTO product) {
//should validate id + from field
}
}
public class ProductDTO {
@NotNull
@NotBlank
private String id;
@Future(groups = GroupFuture.class)
private Date from;
}
Of course the @Valid(with = GroupFuture.class)
statement is invalid. But it shows what I'm trying to achieve.
Is that possible?
Got it. Also having to use the Default.class
group to validate any fields not having a group.
@GetMapping("/sell/product")
public Object sell(@Validated({Default.class, GroupFuture.class}) ProductDTO product) {
}