How to use SpringMVC @Valid to check fields in POST and only non-empty fields in PUT

We are creating a RESTful API with SpringMVC, and we have the endpoint / products where POST can be used to create a new product and PUT to update fields. We also use javax.validation to check the fields.

It works fine in POST, but in PUT, the user can only pass one field, and I can not use @Valid, so I will need to duplicate all the checks made using the annotation with java code for PUT.

Does anyone know how to extend the @Valid annotation and create something like @ValidPresents or something else that solves my problem?

+6
source share
2 answers

You can use validation groups with Spring annotation org.springframework.validation.annotation.Validated .

Product.java

 class Product { /* Marker interface for grouping validations to be applied at the time of creating a (new) product. */ interface ProductCreation{} /* Marker interface for grouping validations to be applied at the time of updating a (existing) product. */ interface ProductUpdate{} @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private String code; @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private String name; @NotNull(groups = { ProductCreation.class, ProductUpdate.class }) private BigDecimal price; @NotNull(groups = { ProductUpdate.class }) private long quantity = 0; } 

ProductController.java

 @RestController @RequestMapping("/products") class ProductController { @RequestMapping(method = RequestMethod.POST) public Product create(@Validated(Product.ProductCreation.class) @RequestBody Product product) { ... } @RequestMapping(method = RequestMethod.PUT) public Product update(@Validated(Product.ProductUpdate.class) @RequestBody Product product) { ... } } 

When using this code, Product.code , Product.name and Product.price will be checked during creation as well as updates. Product.quantity , however, will only be checked during the upgrade.

+6
source

What to do if you implement the Validator interface to customize your verification and reflectively check your restrictions for any type.

8.2 Verification using the Spring s verification interface

0
source

All Articles