I have a RestController with one endpoint. That endpoint accepts object of data class. Data class has 2 attributes. How do I make sure these attributes are validated?
My data class:
data class FormObject(val email: String, val age: Int)
And controller:
@PostMapping("submit")
fun submit(@RequestBody formObject: FormObject): FormObject {
return formObject
}
How do I make sure email is email and age is not bigger than 150? Thanks,
You can use the Bean Validation Framework for this.
1) Annotate the request object as needing validation:
fun submit(@Valid @RequestBody formObject: FormObject): FormObject
^^^^^^
2) Annotate the fields of your data class with the appropriate validation annotations:
data class FormObject(
@field:NotBlank
val email: String,
@field:Min(1)
@field:Max(150)
val age: Int
)
Note that you have to apply the annotation to the field
(not the parameter) or the validation won't happen the way we want. Also, if we define age
as an Int
, it will have a default value (0
) if the caller does not send it, so I applied a the minimum validation on that to offset that (assuming age 0 is not ok, YMMV).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With