I need to limit the number of MultipartFiles sent to Spring Rest API. The annotations from jakarta.validation.constraints don't work for List<MultipartFile> files for some reason, but they do work for lists of other objects, such as List<String> strings for example.
@Valid
@Size(min = 1, max = 2, message = "files.size")
@RequestPart(name = "files")
List<MultipartFile> files,
@Valid
@Size(min = 1, max = 2, message = "strings.size")
@RequestParam(name = "strings")
List<String> strings,
In the above example, more than 2 strings are not allowed by validation, but more than 2 files are allowed.
Please tell me how, preferably, using annotations to limit the number of files in list for the endpoint
To validate the elements of a List, you'll need to implement a custom validator. You can achieve this by creating a custom validator that validates each element of the list individually. Here's an example of how you could do this using Spring's Validator interface: