@Valid annotation is not working in spring boot

17,952

Solution 1

I figured it out... it's because the PurchaseWrapperValidator which implements org.springframework.validation.Validator overrides the default javax.validation.* annotations.

Solution 2

Put a dependency at pom.xml. Or, at start.spring.io select Validation on dependencies.

dependency: groupId org.springframework.boot groupId artifactId spring-boot-starter-validation artifactId

Share:
17,952
Ryan Zhu
Author by

Ryan Zhu

Updated on August 21, 2022

Comments

  • Ryan Zhu
    Ryan Zhu over 1 year

    Here is the scenario, a controller annotated with @RestController and a PUT method whose @RequestBody argument needs to be validated. I use @Valid annotation on the argument and @NotNull,@Min annotations on bean fields, but they are not working.

    Code is here:

    the Bean:

    public class PurchaseWrapper {
      @DecimalMin(value = "0.00",message = "discount must be positive")
      @NotNull
      private BigDecimal discount;
      @NotNull
      private Long merchandiseId;
      @NotNull
      private Long addressId;
      @Min(1)
      @NotNull
      private Integer count;
    }
    

    the Controller

    @RestController
    @RequestMapping("merchandises")
    public class MerchandiseController {
    
    @RequestMapping(value = "purchase",method = RequestMethod.PUT)
    public ResponseEntity<RestEntity> purchase(@Valid @Validated @RequestBody PurchaseWrapper purchaseWrapper,
                                               @RequestParam String token){
        return new ResponseEntity<>(merchandiseService.purchase(purchaseWrapper,token),HttpStatus.OK);
    }
    
    @Autowired
    PurchaseWrapperValidator purchaseWrapperValidator;
    
    @InitBinder(value = "purchaseWrapper")
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(purchaseWrapperValidator);
    }
    }
    

    The pom file:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        <dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
    

    I have no idea what's wrong here... And I guess it's the problem that I use @Valid and @Validated annotations both on the same argument. But even though I omit the @Validated annotation, the @Valid is still not working...

    Any ideas?