I want to apply @Validated
and @Valid
for verifying user input of an HTTP request:
import org.springframework.validation.annotation.Validated
import jakarta.validation.Valid
// ...
@RestController
@RequestMapping("/api/things")
@Validated
class ThingController() {
@Autowired
private lateinit var thingService: ThingService
@PostMapping(consumes = [MediaType.APPLICATION_JSON_VALUE], produces = [MediaType.APPLICATION_JSON_VALUE])
fun createThing(@Valid @RequestBody thing: Thing): ResponseEntity<Thing> {
thingService.createThing(thing)
return ResponseEntity.ok(thing);
}
}
@Entity
@Table(name = "thing")
@JsonIgnoreProperties(ignoreUnknown = true)
data class Thing(
@Id @JsonIgnore
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
@Size(min = 5, max = 20)
val title: String,
@NotNull
@Size(min = 5, max = 20)
val description: String
)
The validation does not throw an error and invalid objects are persisted:
curl --location 'localhost:8080/api/things' \
--header 'Content-Type: application/json' \
--data '{
"description": "tooooooooooooooooooooooo longgggggggggggggggggg",
"title": "x",
}'
=> 200 OK
Comment From: snicoll
@schirrmacher please share a small sample that we can run ourselves rather than partial code in text. You can share it with us by pushing the sample to a GitHub repo or attaching a zip to this issue.
Moving to the Spring Framework issue tracker.
Comment From: cah-sourabh-singh
Even, I am facing the same issue.
Comment From: schirrmacher
Sorry for the late response, here an example: Example.zip
Comment From: sdoshi96
I was able to replicate this issue using the attached Example zip file
Comment From: sdeleuze
As documented here:
If you use bean validation on classes with properties or a primary constructor parameters, you may need to use annotation use-site targets, such as
@field:NotNull
or@get:Size(min=5, max=15)
, as described in this Stack Overflow response.
As a consequence, I am closing this issue.
Comment From: charu-jain-sapient
I am facing similar issue with spring boot 3.1.5 and I am using Java language. Can anyone please help me with the solution.
Comment From: snicoll
@charu-jain-sapient this issue is Kotlin specific so it can't be the same. If you're looking for support, please ask a question on StackOverlow. If you believe you've found a bug, please create a separate issue with a small sample we can run ourselves to reproduce. Thanks!
Comment From: mohaned122
i had the same error but i figure it out with that:
i add the dependency:
Comment From: isole
Doesn't work for me with 3.2.5
Comment From: greeneley
jakarta.validation version 3.0.2 seems not working. I replaced this library by javax validation and it perfectly works.