How does it work for the server validation. I can’...
# ktor
d
How does it work for the server validation. I can’t just add error message without telling the front end, which key the error belongs to. I have :
Copy code
validate<CreatePostRequest> { req ->
            var errors = mutableListOf<String>()
            if (req.title?.length!! < 4) {
                errors.add("title should have at least 4 characters")
            }
            if (req.body?.length!! < 4) {
                errors.add("body should have at least 4 characters")
            }

            if (errors.isNotEmpty())
                ValidationResult.Invalid(errors)
            else ValidationResult.Valid
        }
which doesn’t work because I have two errors.
a
You can thrown an exception of a custom type inside the
validate
’s block to carry a necessary information about the errors to the
StatusPages
plugin. Here is an example:
Copy code
fun main() {
    embeddedServer(Netty, port = 3333, host = "0.0.0.0") {
        install(ContentNegotiation) {
            json()
        }
        install(StatusPages) {
            exception<CreatePostRequestValidationException> { call, cause ->
                call.respond(status = HttpStatusCode.BadRequest, message = mapOf("errors" to cause.errors))
            }
        }
        install(RequestValidation) {
            validate<CreatePostRequest> { req ->
                val errors = mutableMapOf<String, String>()
                if (req.title?.length!! < 4) {
                    errors["title"] = "title should have at least 4 characters"
                }
                if (req.body?.length!! < 4) {
                    errors["body"] = "body should have at least 4 characters"
                }

                if (errors.isNotEmpty()) {
                    throw CreatePostRequestValidationException(errors)
                }

                ValidationResult.Valid
            }
        }

        routing {
            post("/") {
                call.receive<CreatePostRequest>()
            }
        }

    }.start(wait = true)
}
👍 2
d
Thanks a lot @Aleksei Tirman [JB] Any way I could get access to the AcceptLanguage header from
fun Application.registerValidation() {
? I want to translate my validation messages : https://github.com/danygiguere/ktor_validation/blob/main/src/main/kotlin/com/example/plugins/Validation.kt. I usually get the AccecptLanguage header with
Copy code
call.request.acceptLanguage()
a
Unfortunately, there is no access to the request in a validation’s block. You can pass i18n messages down to the
StatusPages
plugin where the request can be accessed via the
call
object.
👍 1
d
Thanks @Aleksei Tirman [JB]. I ended up building my own implementation : https://github.com/danygiguere/ktor_validation/tree/main/src/main/kotlin/com/example.