diogo beato
diogo beato

Reputation: 175

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?

Upvotes: 8

Views: 2345

Answers (2)

manish
manish

Reputation: 20135

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.

Upvotes: 8

user5568909
user5568909

Reputation: 1

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

Upvotes: 0

Related Questions