micronaut-core icon indicating copy to clipboard operation
micronaut-core copied to clipboard

Validate collection and elements

Open aentwist opened this issue 3 years ago • 2 comments

Issue description

I am trying to validate a List<String> from a request. The list should have some constraints, and its elements should also have some. Using @NotEmpty and @Size on the list are working. How can I validate the elements to be @NotBlank?

I have tried using @NotBlank.List. Is this correct usage? It doesn't work.

package com.example.micronautvalidation.controllers

import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Post
import io.micronaut.validation.Validated
import javax.validation.constraints.*

@Validated
@Controller("/hello")
class HelloController {

    @Post
    def index(@NotEmpty @NotBlank.List @Size(max = 2) List<String> texts) {
        HttpResponse.ok(texts)
    }
}

I have also tried using @NotBlank but on the list's generic type instead of the list (I see this is documented by https://github.com/micronaut-projects/micronaut-core/issues/1814 as not supported). The suggested workaround is to use,

@Valid
@NotBlank

but if @Valid applies all the annotations to the elements, then how can I validate the list with @NotEmpty and @Size?

The documentation is lacking here, just saying that all jakarta validation constraints are on the table. There is a simple String example and are POJO examples, but I do not see any collection examples like I have described.

We can validate parameters using javax.validation annotations and the Validated annotation at the class level.

I see https://github.com/micronaut-projects/micronaut-core/issues/4410, which appears to be related.

This could be a bug, feature request, or documentation issue?

Right now I can think to validate the elements with constraints, and to validate the collection manually. This is reinventing the wheel for sure.

aentwist avatar Jun 02 '22 02:06 aentwist

There is a PR https://github.com/micronaut-projects/micronaut-core/pull/5240 being worked on to address this that is targeting Micronaut 4.0

graemerocher avatar Jun 02 '22 10:06 graemerocher

Can you please confirm that this is still an issue in the latest version of Micronaut?

ojebari-ma avatar May 25 '25 23:05 ojebari-ma