DEV Community

Cover image for Spring Boot Validation in Kotlin with @field
Parker Drake for Focused

Posted on • Edited on • Originally published at focusedlabs.io

10 3

Spring Boot Validation in Kotlin with @field

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)
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay