1

@Valid annotation is not calling validator when @RequestPart is used. In other places I used @Valid with @RequestBody and it works fine. There is no error just passing the wrong validation also.

Below is the code.

@InitBinder("campaignCreatorDTO")
public void initCreatorDTOBinder(WebDataBinder binder) {

    binder.addValidators(new CreatorDTOValidator());
}

@PostMapping(value = "/creator", consumes = {"multipart/form-data"}, produces = {"application/json"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public @Valid
ResponseDTO creator(@Valid @RequestPart("json") CampaignCreatorDTO campaignCreatorDTO,
                    @RequestPart(name = "file", required = false) MultipartFile adGraphic) {
}
Anjali
  • 1,623
  • 5
  • 30
  • 50
  • You are overriding the validator and bind it to a model attribute. Remove the `"campaignCreatorDTO"` from the `@InitBinder` and try again. If that fails(because you then set the global validator) try using the argument name `json` instead of the model argument name. – M. Deinum Nov 06 '18 at 12:35

2 Answers2

1

As detailed here, @InitBinder uses the value passed to it for targeted validation with same named request parameters or model attributes. The problem is that you have neither since you utilize a multipart form data input in your particular endpoint /creator. Therefore removing the naming restriction from the @InitBinder would be the solution.

@InitBinder
public void initCreatorDTOBinder(WebDataBinder binder) { ... }
buræquete
  • 14,226
  • 4
  • 44
  • 89
0

Run validation in the controller method using Validator Bean:

org.springframework.validation.Validator

@Autowired
protected Validator validator;

PostMapping(value = "/creator", consumes = {"multipart/form-data"}, produces = {"application/json"})
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public @Valid
ResponseDTO creator(@RequestPart("json") CampaignCreatorDTO campaignCreatorDTO,
                    @RequestPart(name = "file", required = false) MultipartFile adGraphic) {
    validator.validate(campaignCreatorDTO);
}
Raheela Aslam
  • 452
  • 2
  • 13
  • still not calling validator. same issue persists. – Anjali Nov 06 '18 at 11:49
  • I had already tried above code and it does not call validator. – Anjali Nov 06 '18 at 12:06
  • Please have a look into below link: https://stackoverflow.com/questions/21329426/spring-mvc-multipart-request-with-json and also provide more detail creatorDTO and CampaignCreatorDTO. – Raheela Aslam Nov 06 '18 at 12:09
  • @Anjali have a look at this post https://stackoverflow.com/questions/31175009/valid-annotation-is-not-working-in-spring-boot use this import org.springframework.validation.Validator – Tara Nov 06 '18 at 12:13