1

I use Kotlin and Spring. I can validate the values using normal 'if's and exceptions but at least in theory there is a validation method provided by the framework

According to the docs and posts on the internet the following should be sufficient:

data class Person(@Min(18) var age: Int, @Size(max=10) val name: String) {
}

and the controller:

@RestController
class PersonController {
    val persons = mutableListOf<Person>()
    @GetMapping
    fun getPeople() = persons

    @PostMapping
    fun sendPerson(@Valid @RequestBody person: Person) {
        persons.add(person)
    }
}

My build.gradle contains the following 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'
implementation 'org.jetbrains.kotlin:kotlin-reflect'

(versions are 3.1.3)

Why the annotations do not seem to do anything and how to fix it?

1 Answers1

1

As pointed by a comment: Kotlin creates at least a field, a getter and a constructor parameter with the syntax, so we need to tell exactly what we want to validate

TLDR: Just change to @get:Valid

Fedor
  • 17,146
  • 13
  • 40
  • 131