Skip to Content
Course content

136: Practice Exercise: Building a Validated Form Parser with Cats

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've all been there: you're filling out a long registration form, you hit "Submit," and the page refreshes with a single error: "Invalid Email." You fix the email, hit submit again, and now it tells you "Password too short." You do this four or five times, getting hit with one error at a time, and by the time the form actually submits, you're already annoyed with the product. As developers, we often do this accidentally because we reach for the most familiar tool in our kit—the Either monad.

The fail-fast trap of Either

When I first started using Either for validation, it felt like the perfect fit. I could wrap each check in a function returning Either[String, A] and chain them together using a for comprehension. It's clean, it's readable, and it handles the "unhappy path" explicitly. But here is the problem: Either is designed for sequential computation. It is "fail-fast."

case class User(email: String, age: Int, username: String)

def validateEmail(email: String): Either[String, String] = 
  if (email.contains("@")) Right(email) else Left("Invalid email")

def validateAge(age: Int): Either[String, Int] = 
  if (age >= 18) Right(age) else Left("Must be at least 18")

def validateUsername(name: String): Either[String, String] = 
  if (name.length >= 3) Right(name) else Left("Username too short")

// The naive way: chaining with for-comprehensions
def parseUser(email: String, age: Int, name: String): Either[String, User] = {
  for {
    vEmail <- validateEmail(email)
    vAge   <- validateAge(age)
    vName  <- validateUsername(name)
  } yield User(vEmail, vAge, vName)
}

If you pass an invalid email and an invalid age into this function, you'll only ever see the email error. The for comprehension stops at the first Left it encounters. In a backend API, this might be acceptable, but for a UI-driven form, it's a poor experience. We aren't just looking for the first thing that went wrong; we want a comprehensive list of everything that went wrong.

Accumulating errors with Validated

This is where cats.data.Validated comes in. Unlike Either, Validated isn't a monad—it's an applicative. I know that sounds like academic jargon, but in practical terms, it means Validated doesn't care about the result of the previous check to decide if it should run the current one. It allows us to run a set of independent checks and "accumulate" the failures.

To make this work, we use ValidatedNel[E, A]. The "Nel" stands for NonEmptyList. We use this instead of a standard List because if a validation fails, we know for a fact there is at least one error. It saves us from having to handle an empty list of errors in our logic.

import cats.data.ValidatedNel
import cats.implicits._

def validateEmailV(email: String): ValidatedNel[String, String] = 
  if (email.contains("@")) email.validNel else "Invalid email".invalidNel

def validateAgeV(age: Int): ValidatedNel[String, Int] = 
  if (age >= 18) age.validNel else "Must be at least 18".invalidNel

def validateUsernameV(name: String): ValidatedNel[String, String] = 
  if (name.length >= 3) name.validNel else "Username too short".invalidNel

def parseUserV(email: String, age: Int, name: String): ValidatedNel[String, User] = {
  (
    validateEmailV(email),
    validateAgeV(age),
    validateUsernameV(name)
  ).mapN(User.apply)
}

The trade-off: Sequence vs. Independence

You might be wondering why we don't just use Validated for everything. There is a real cost: you lose the ability to make one validation dependent on another. For example, if you have a field "Confirm Password," you can't validate that it matches the first password until you know the first password itself is valid. Validated cannot do this because it's not sequential.

My rule of thumb is this: if your validations are independent (like checking different fields in a form), use ValidatedNel. If you have a pipeline where step B requires the output of step A, stick with Either. In many complex systems, I actually use both—I'll use Validated to scrub the initial input and then convert the result to an Either using .toEither once I need to start performing sequential business logic.




📋 Practical Task

Exercise: Implementing a Comprehensive User Registration Validator with ValidatedNel

You are tasked with building a robust validation layer for a new user signup process. You need to ensure that the input data is clean before it ever hits your database.

Requirements:

  • Create a case class RegistrationDetails(email: String, age: Int, password: String, newsletter: Boolean).
  • Implement the following validation rules using ValidatedNel[String, A]:
    • Email: Must contain both an '@' and a '.'
    • Age: Must be between 13 and 120 (inclusive).
    • Password: Must be at least 8 characters long and contain at least one digit.
  • Write a function validateRegistration(email: String, age: Int, password: String, newsletter: Boolean): ValidatedNel[String, RegistrationDetails] that aggregates all errors if any of the above rules fail.
  • Test your implementation with two scenarios:
    1. Input that is completely invalid (should return a NonEmptyList containing three distinct error messages).
    2. Input that is completely valid (should return the RegistrationDetails object).

Hint: Remember to import cats.implicits._ to get access to the mapN syntax and the .validNel / .invalidNel extension methods.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.