Context: I'm using micronaut version 3.4.2 and Kotlin 1.7.22. I have a Data class in another project which I download as a dependency Jar. The javax field validations are not working in the controller layer.
My data Class:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class ItemsTO(
@field:Min(value = 1, message = "Minimum quantity has to be 1") val quantity: Int
)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class RequestTO(
val items: List<ItemsTO>
)
My Controller:
@Post("/")
@Status(HttpStatus.CREATED)
fun handleRequest(@Valid @Body requestTO: RequestTO): ResponseTO {}
Reading the documentation I saw that @Introspected
is required. I added that annotation as well as @Validated
on the controller but it's still doesn't validate the request body; the request goes through. I saw in some other projects where this is implemented and they don't use @Introspected or @Validated annotations.
In the project having the controller(where the data class containing module is imported) I have these in my build.gradle
implementation "io.micronaut:micronaut-validation"
kapt "io.micronaut:micronaut-inject-java"
kapt "io.micronaut:micronaut-validation"
I'm not able to figure out what the issue is and why the fields in the request body are not being validated
Found the issue. In my code I have two data classes. The validation message I'm expecting is from the data class{
ItemsTO
) used as a type in another data class(RequestTO
) fielditems
. Now the request body will be of typeRequestTO
hence for the validation onItemsTO
to work we need the request body class to be:We have to add
@field:@Valid
on the field whose data class is getting validated.ref: https://www.baeldung.com/kotlin/valid-spring-annotation#4-validating-nested-objects