Back to code Kotlin

Validar un formulario y devolver todos los errores juntos

Una función que revisa todos los campos y devuelve la lista completa de problemas, no solo el primero.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

Un formulario que avisa de a un error por vez obliga a enviar cinco veces. Hay que validar todo y contestar con la lista completa.

Kotlin
sealed class Validacion {
    object Ok : Validacion()
    data class Error(val campo: String, val motivo: String) : Validacion()
}

data class Registro(val nombre: String, val correo: String, val edad: Int)

fun validar(r: Registro): List<Validacion.Error> = buildList {
    if (r.nombre.isBlank()) add(Validacion.Error("nombre", "es obligatorio"))
    if (!Regex("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$").matches(r.correo)) add(Validacion.Error("correo", "no parece un correo"))
    if (r.edad !in 18..120) add(Validacion.Error("edad", "debe estar entre 18 y 120"))
}

fun main() {
    val errores = validar(Registro("", "ana@ejemplo", 17))
    if (errores.isEmpty()) println("Registro válido")
    else errores.forEach { println("${it.campo}: ${it.motivo}") }
}

Why it is written this way

  1. buildList arma la lista mientras se evalúan las reglas: cada if agrega su error sin cortar las demás.
  2. Cada error dice a qué campo pertenece, así la pantalla puede pintarlo junto al campo correcto.
  3. r.edad !in 18..120 se lee como se dice: "la edad no está entre 18 y 120".
  4. La data class da gratis la igualdad y el texto legible, útil para probar.
How to try it

Pegalo en play.kotlinlang.org o guardalo como validar.kt y corré: kotlinc validar.kt -include-runtime -d v.jar && java -jar v.jar

Watch out

Esta validación es de formato. Que el correo exista o que no esté ya registrado se comprueba en el servidor, y siempre en el servidor aunque también se valide en la app.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo esta validación de formulario en Kotlin que devuelve todos los errores juntos. Adaptala a mi formulario, que tiene estos campos y reglas: [CAMPOS Y REGLAS]. Agregá reglas que dependen de dos campos a la vez (por ejemplo [REGLA CRUZADA]) y mensajes listos para mostrar en [IDIOMA]. Que siga devolviendo la lista completa, no el primer error.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.
You are writing outside working hours. I will read you as soon as the day starts.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.