Field-level validation returning an error map
Kotlin
data class Signup(val email: String, val age: Int, val password: String)
fun validate(input: Signup): Map<String, String> = buildMap {
val email = input.email.trim()
if (email.count { it == '@' } != 1 || email.startsWith('@') || email.endsWith('@')) {
put("email", "must contain a single @ and no edge @")
}
if (input.age !in 18..130) put("age", "must be between 18 and 130")
if (input.password.length < 8) put("password", "must be at least 8 characters")
}
val errors = validate(Signup("bad", 12, "short"))
check(errors.keys == setOf("email", "age", "password"))