Why we need to put both annotation to make validation to work?
If I put only one annotation, than validation is not working.
@Validated
@Controller("/")
open class HelloController {
@Post("/signup")
open fun signup(@Body @Valid dto: SignUpDto): String {
println("${dto.email} ${dto.password}")
return "OK"
}
}
class SignUpDto @JsonCreator constructor(
@JsonProperty("email") @field:Size(max=5) val email: String,
@JsonProperty("password") val password: String)
Also, why validation is not done for nested object?
class SignUpDto @JsonCreator constructor(
@JsonProperty("email") @field:Size(min=5) val email: String,
@JsonProperty("password") val password: String,
@JsonProperty("address") val address: AddressDto)
class AddressDto @JsonCreator constructor(
@JsonProperty("country") @field:Size(min=3) val country: String )
country field is not validated for request { "email": "[email protected]", "password": "LOL", "address": { "country": "US" } }
The 2 annotations mean different things. @Valid is used to control cascading validation. If you want AddressDto to cascade validation you have to annotate address with @Valid.
This is not really related to Micronaut but how Bean validation is Java works https://beanvalidation.org/2.0/spec/#constraintdeclarationvalidationprocess-requirements-graphvalidation
If you want AddressDto to cascade validation you have to annotate address with @Valid.
Is it possible to fix this somehow in Micronaut? because it can leads to mistakes, if you forgot to put that annotation
Current versions of Micronaut use Hibernate Validator we may in the future replace this and it could be possible to add a configuration option, but since we cannot change Hibernate Validator's behaviour today we cannot change it
Ok thanks.
What about that @Vaild in method does not work if controller is not annotated with @Validated?
that we can maybe fix by automatically annotating a bean with @Validated if @Valid is present
It might be possible to imply the presence of @Validated whenever @Valid or any specific Bean Validation constraint is present. That'd be akin to what the CDI integration of BV is doing for method validation, too.
@gunnarmorling yes that it possible, and will be a nice improvement. Thanks for the feedback