7

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,

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.