Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot validation annotation not working for Kotlin

Tags:

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?

like image 919
ttt Avatar asked Jan 25 '18 12:01

ttt


2 Answers

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)
like image 154
zsmb13 Avatar answered Sep 21 '22 13:09

zsmb13


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)
like image 32
jax Avatar answered Sep 21 '22 13:09

jax