Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller validation in Kotlin Spring Boot

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,

like image 292
Bartosz Avatar asked Dec 22 '22 21:12

Bartosz


1 Answers

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).

like image 195
Todd Avatar answered Dec 25 '22 10:12

Todd