3
votes

I'm writing a project in Kotlin and have this in a controller:

@PostMapping("/token")
fun generateToken(@RequestBody @Valid credentials: Credentials) { /* something */ }

data class Credentials(@Email @NotBlank val email: String,
                       @NotBlank val password: String)

By default @Valid annotation tells Spring to validate object fields. But Kotlin places constraint annotations on the constructor parameters, so validation doesn't work. To make it work I have to define use-site targets for annotations:

data class Credentials(@field:Email @field:NotBlank val email: String,
                       @field:NotBlank val password: String)

which is annoying and adds visual garbage. Is it possible to configure Spring to validate constructor parameters?

1

1 Answers

0
votes

There isn't a whole lot you can do. You can make it look a little better by combining annotations for each field, e.g.:

data class Credentials(@field:[Email NotBlank] val email: String,
                   @field:NotBlank val password: String)

Other than that, your only other options are:

  1. Manually configured Spring validation classes

  2. Validating the data within your code body