Skip to main content

yoshi

A validation library that transforms untyped input into domain types — not just checking values, but parsing them into a stronger representation.

Setup​

libraryDependencies += "dev.hshn" %% "yoshi-core" % "0.6.0"

The idea​

Most validation libraries give you Validated[E, A] — a value that's either valid or not. Yoshi gives you Validation[V, A, B] — a composable function from A to B that accumulates violations on failure.

// Untyped input — what you receive
case class FormInput(
name: Option[String],
age: String,
items: List[FormInput.Item],
)
object FormInput:
case class Item(label: Option[String])

// Domain type — what you want
case class Order(
name: String,
age: Int,
items: List[Order.Item],
)
object Order:
case class Item(label: String)
given Validation[Violation, FormInput.Item, Order.Item] =
Validation.cursor[FormInput.Item] { c =>
(
c.validateAs[String](_.label)
).validateN { label =>
Order.Item(label)
}
}

val validation: Validation[Violation, FormInput, Order] =
Validation.cursor[FormInput] { c =>
(
c.validateAs[String](_.name),
c.validateAs[Int](_.age),
c.validateAs[List[Order.Item]](_.items),
).validateN { case (name, age, items) =>
Order(name, age, items)
}
}

The cursor derives field names from accessor lambdas at compile time — no manual .at("field") strings needed.

When the path should differ from the field name, use field() with .at() to override:

val renamed: Validation[Violation, FormInput, Order] =
Validation.cursor[FormInput] { c =>
(
c.field(_.name).at("display_name").validateAs[String],
c.validateAs[Int](_.age),
c.validateAs[List[Order.Item]](_.items),
).validateN { case (name, age, items) =>
Order(name, age, items)
}
}

Path-aware error accumulation​

Violations carry the full path to where they occurred:

val invalid = FormInput(
name = None,
age = "abc",
items = List(
FormInput.Item(Some("pen")),
FormInput.Item(None),
),
)
validation.run(invalid).left.map(_.toList)
// res0: Either[List[Tuple2[Paths, Violation]], Order] = Left(
// List(
// (Paths(List(Key("age"))), NonIntegerString("abc")),
// (Paths(List(Key("items"), Index(1), Key("label"))), Required),
// (Paths(List(Key("name"))), Required)
// )
// )

Rules across fields​

A rule that no single field can decide — an upper bound that must not fall below its lower bound — belongs to the type it protects, usually as a smart constructor. Lift it with Validation.fromEither into a Validation whose input is the tuple of validated fields, and continue the tuple into it with andValidateAs:

case class BoundsInput(lower: String, upper: String)
case class Bounds(lower: Int, upper: Int)
object Bounds:
def from(lower: Int, upper: Int): Either[Violation, Bounds] =
if lower <= upper then Right(Bounds(lower, upper))
else Left(Violation.TooSmall(upper, lower))

given Validation[Violation, (Int, Int), Bounds] = Validation.fromEither(Bounds.from.tupled)

val bounds: Validation[Violation, BoundsInput, Bounds] =
Validation.cursor[BoundsInput] { c =>
(
c.validateAs[Int](_.lower),
c.validateAs[Int](_.upper),
).andValidateAs[Bounds]
}

The rule runs only once every field has validated, so a field that fails on its own is not reported twice. Since no single field owns the rule, its violation sits at the path of the combination — here, the root:

bounds.run(BoundsInput("x", "3")).left.map(_.toList)
// res1: Either[List[Tuple2[Paths, Violation]], Bounds] = Left(
// List((Paths(List(Key("lower"))), NonIntegerString("x")))
// )
bounds.run(BoundsInput("10", "3")).left.map(_.toList)
// res2: Either[List[Tuple2[Paths, Violation]], Bounds] = Left(
// List((Paths(List()), TooSmall(value = 3, min = 10)))
// )

The root is the right place when the input nests the fields under a key of their own, as in c.validateAs[Bounds](_.bounds). When the input is flat while the domain groups the values, a form usually shows the violation beside one of the inputs instead. Where it goes is a fact about the input's shape, not about the rule, so pass the path to andValidateAs and let the cursor derive it:

val boundsBesideUpper: Validation[Violation, BoundsInput, Bounds] =
Validation.cursor[BoundsInput] { c =>
(
c.validateAs[Int](_.lower),
c.validateAs[Int](_.upper),
).andValidateAs[Bounds](c.path(_.upper))
}

Only the rule's violation moves; each field's own stays at its path. .at(...) after the chain would move both:

boundsBesideUpper.run(BoundsInput("x", "3")).left.map(_.toList)
// res3: Either[List[Tuple2[Paths, Violation]], Bounds] = Left(
// List((Paths(List(Key("lower"))), NonIntegerString("x")))
// )
boundsBesideUpper.run(BoundsInput("10", "3")).left.map(_.toList)
// res4: Either[List[Tuple2[Paths, Violation]], Bounds] = Left(
// List((Paths(List(Key("upper"))), TooSmall(value = 3, min = 10)))
// )

validateN, validateWith and andValidateAs take a single result and a tuple of them alike, so a validation keeps compiling as its fields come and go.

Automatic container derivation​

Define a validator for A → B, and validators for Option[A], List[A], Set[A], Map[String, A] are derived automatically:

import yoshi.*
import yoshi.defaults.*

// Given this exists:
// given Validation[Violation, String, Int] (from yoshi.defaults)

// These are derived for free:
summon[Validation[Violation, Option[String], Option[Int]]]
summon[Validation[Violation, List[String], List[Int]]]
summon[Validation[Violation, Set[String], Set[Int]]]
summon[Validation[Violation, Map[String, String], Map[String, Int]]]

Any collection validates into a Set[B], so a List[String] field can be validated straight into a Set[Int]. The index in a violation path follows the input's iteration order, so validate from an ordered collection where the path has to be stable.

Required fields​

An Option input says the value may be absent. The type you validate it into says whether your domain accepts that:

import yoshi.*
import yoshi.defaults.*

// Optional: None passes through
summon[Validation[Violation, Option[String], Option[Int]]]

// Required: None fails with Violation.Required
summon[Validation[Violation, Option[String], Int]]

The violation to report for an absent value cannot be derived, since Validation does not know your violation type. yoshi.defaults supplies it for its own type; for a violation type of your own, define a single Required instance and the derivations above become available:

import yoshi.*

enum MyViolation:
case Missing
case NotAnInt(value: String)

given Required[MyViolation] = Required(MyViolation.Missing)
given Validation[MyViolation, String, Int] = Validation.parseInt(MyViolation.NotAnInt(_))

summon[Validation[MyViolation, Option[String], Int]]

Composing validators​

val nonEmpty: Validation[String, String, String] =
Validation.ensure("required")((_: String).nonEmpty)

val maxLen: Validation[String, String, String] =
Validation.maxLength(100)((_, _) => "too long")

// Accumulating — collects all violations
val both = nonEmpty |+| maxLen

// Sequential — short-circuits on first failure
val chain = nonEmpty >> maxLen