I have a very similar problem to this topic @Valid annotation is not validating the list of child objects but trying to implement using Kotlin.
The @Valid
annotation is not working for WordDto
. Only the class MessageDto
is evaluated.
@SpringBootApplication
class ValidationsApplication
fun main(args: Array<String>) {
runApplication<ValidationsApplication>(*args)
}
data class WordDto(
@field:Max(5)
val word: String
)
data class MessageDto(
@Valid
@field:NotEmpty
val words: List<WordDto>
)
@RestController
class Controller {
@PostMapping("/hello")
fun hello(@Valid @RequestBody messageDto: MessageDto) {
messageDto.words.map(System.out::println)
}
}
I've tried this approach too:
val words: List<@Valid WordDto>
Also wrote this test that should be passing:
@Test
fun `should validate child objects`() {
val dto = MessageDto(
words = listOf(
WordDto("Long Word that should fail")
)
)
val violations = validator.validate(dto)
assertThat(violations).isNotEmpty()
}
Dependencies:
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
Any ideas of what could be missing?
The project can be found in Github