Spring webflux bean validation not working

Jan Wytze :

I am trying to use bean validation in Webflux. This is what I have so far:

@PostMapping("contact")
fun create(@RequestBody @Valid contact: Mono<Contact>) : Mono<Contact> {
    return contact.flatMap { contactRepository.save(it) }
            .doOnError{ Error("test") }
}

The The validation doesn't work... I would expect that the Error("test") would be shown...

Does someone has a working example(Java or Kotlin)?

UPDATE

Here is a repository so it can be reproducted: https://github.com/jwz104/webflux-validation-test

Request:

curl --request POST \
  --url http://localhost:8080/tickets \
  --header 'content-type: application/json' \
  --data '{
    "email": "",
    "name": "",
    "message": ""
}'

Renamed contact to ticket, but everything is still the same.

zsmb13 :

The annotations you have placed in the example project are actually annotations on the constructor parameters of the Ticket class. For Spring validation, you need to annotate the fields instead. You can do this in Kotlin by using annotation use-site targets.

In this specific case, your Ticket class should look like this:

data class Ticket(
        @field:Id
        @field:JsonSerialize(using = ToStringSerializer::class)
        val id: ObjectId = ObjectId.get(),

        @field:Email
        @field:Max(200)
        @field:NotEmpty
        val email: String,

        @field:NotEmpty
        @field:Size(min = 2, max = 200)
        val name: String,

        @field:NotEmpty
        @field:Size(min = 10, max = 2000)
        val message: String
)

This, along with the following controller function will work and return errors as expected:

@PostMapping("tickets")
fun create(@RequestBody @Valid contact: Mono<Ticket>) : Mono<Ticket> {
    return contact.flatMap { ticketRepository.save(it) }
            .doOnError{ Error("test") }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=444641&siteId=1