How to use @Valid with @PutMapping when Request Body is a List of dataclass in Kotlin Spring boot?

199 Views Asked by At

@Valid is not working with @PutMapping where Request Body is List of dataclass in Kotlin Spring boot

have added the library for it in the gradle.build.kts

implementation("org.springframework.boot:spring-boot-starter-validation")

then tested for the below scenario it worked

@PutMapping(@Valid @RequestBody upsertData: UpsertData): ResponseEntity<String> {
        
        }

data class UpsertData {
    @field:NotBlank(message = "Name must not be blank")
    val naName: String,
    @field:Min(value = 18, message = "Age must be at least 18")
    val age: Int
}

but when I tried for below it is not validating the input

@PutMapping(@Valid @RequestBody upsertData: List<UpsertData>): ResponseEntity<String> {

}

I also tried by adding @Valid for the dataclass only but still this is failing...

@PutMapping(@Valid @RequestBody upsertData: List<@Valid UpsertData>): ResponseEntity<String> {

}

Can someone please help me here...

2

There are 2 best solutions below

0
On

try following because Kotlin declaritve is not same as Java;

@field:Valid
3
On

you can try with removing Outer @Valid option

@PutMapping(@RequestBody upsertData: List<@Valid UpsertData>): ResponseEntity<String> {

}

or you can refer below sample code which is working for me

@RestController
@Validated
class MyController {
    @GetMapping("/srch")
    fun getSearchResult(
        @Valid
        @RequestParam(value = "term") terms: List<Term>,
    ): Mono<ResponseEntity<SearchResponse>> {...}
}