Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SpringMVC @Valid to validate fields in POST and only not null fields in PUT

We are creating a RESTful API with SpringMVC and we have a /products end point where POST can be used to create a new product and PUT to update fields. We are also using javax.validation to validate fields.

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

Anyone knows how to extend the @Valid annotation and creating something like @ValidPresents or something else that solve my problem?

like image 892
diogo beato Avatar asked Nov 16 '15 18:11

diogo beato


1 Answers

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

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) { ... }
}

With this code in place, Product.code, Product.name and Product.price will be validated at the time of creation as well as update. Product.quantity, however, will be validated only at the time of update.

like image 73
manish Avatar answered Nov 07 '22 20:11

manish