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

不羁岁月 提交于 2019-12-03 13:48:11

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.

What if you implements the interface Validator to customize your validation and by reflection check your constraints for any Type.

8.2 Validation using Spring’s Validator interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!