Spring webflux bean validation not working

后端 未结 3 1587
南笙
南笙 2021-02-15 17:56

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

@PostMapping(\"contact\")
fun create(@RequestBody @Valid contact: Mono)         


        
3条回答
  •  情书的邮戳
    2021-02-15 18:43

    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) : Mono {
        return contact.flatMap { ticketRepository.save(it) }
                .doOnError{ Error("test") }
    }
    

提交回复
热议问题