Spring Boot Validation in Kotlin with @field
When validating fields in a Spring Boot controller written in Kotlin, the key is using @field annotations in data classes. Without it, Kotlin applies validation to constructor parameters by default.
Jan 28, 2021

Recently I found myself needing to validate fields in a Spring Boot controller written in Kotlin. Here's the code I ended up with:
@Controller
@RequestMapping("api/sample")
class SampleController {
@PostMapping
fun post (@Valid @RequestBody request: SampleType){
return ResponseEntity.ok().build()
}
}
data class SampleType(@field:NotBlank info: String)The key is the @field in the data class. Without that, Kotlin will apply validation to the constructor parameters by default. This makes sense when you see it, but is less obvious when you're wading through your 10th Java based tutorial on Spring validation.
Hope this helps!
We’ll use the information you provide to respond to your enquiry. Learn more about how we handle your personal data in our Privacy Policy.
