How do we do kotlin data class validation on Collection?

Try this:

data class KotlinUser(
    @field:NotEmpty
    @field:NotNull
    @field:Pattern(regexp = "[a-z]*", message = "Only lower case first name")
    val name: String,

    @field:Valid
    @field:NotEmpty
    val phones: List<Phone>
)

data class Phone(
    @NotBlank
    @Pattern(regexp = "\\d{10}", message = "Only 10 digits")
    val phoneNumber: String?
)

This is currently not supported. The Kotlin compiler currently ignores annotations on types.

See for details:

  • https://discuss.kotlinlang.org/t/i-have-a-question-about-applying-bean-validation-2-0/5394
  • Kotlin data class and bean validation with container element constraints

There are also issues on the Kotlin issue tracker for this:

  • https://youtrack.jetbrains.net/issue/KT-26605
  • https://youtrack.jetbrains.net/issue/KT-13228

The latter has target version 1.4.