ttt
ttt

Reputation: 4004

Spring boot validation annotation not working for Kotlin

I got a simple data class for Kotlin

data class Person(val name: String, @get: Min(18) val age: Int)

I actually build this class from a CSV file and I read the CSV using apache CSV parser. Even I have some data which is less than 18 for age field, the test still passed no error.

Looks like this annotation is not working for Kotlin?

Upvotes: 5

Views: 2025

Answers (2)

jax
jax

Reputation: 38643

Try adding the annotation@Validated to the class (might just work for spring beans though). These annotations do not prevent the value being set they simply allow getting a BindingResult with a list of validation errors from an existing instance. If you need to prevent a value being set you can use a custom delegate.

 val age: Int by MyDelegates.min(18)

Upvotes: 1

zsmb13
zsmb13

Reputation: 89608

You're currently annotating the constructor parameter with the Min annotation - I believe you should annotate the field instead, with a use-site target like this:

data class Person(val name: String, @field:Min(18) val age: Int)

Upvotes: 3

Related Questions