Validation that collects every error
An operator registers a webhook source in Relay with a form: name, URL, retry count, secret. They
get the name wrong, the URL wrong, and the secret too short. With a flatMap chain, Relay says
“name must be 1-32 characters”. They fix it, submit, and now it says “url must start with https://”.
Three round trips for one form.
For form input the user wants every error at once. This lesson builds that, and explains why the tool from the last two lessons cannot.
flatMap stops at the first error
Section titled “flatMap stops at the first error”flatMap runs the next step only if the previous one succeeded. That is what you want when step two
needs step one’s output. For independent fields it is the wrong shape:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }declare const flatMap: <A, B, F>(f: (a: A) => Result<B, F>) => <E>(r: Result<A, E>) => Result<B, E | F>declare const ok: <A>(a: A) => Result<A, never>declare function validateName(s: string): Result<string, "BadName">declare function validateUrl(s: string): Result<string, "BadUrl">
declare const input: { readonly name: string; readonly url: string }
const source = flatMap((name: string) => flatMap((url: string) => ok({ name, url }))(validateUrl(input.url)))( validateName(input.name),)// a bad name hides a bad url: validateUrl is never even calledThe second validator never runs after a failed first one. To report both, run both, then combine.
Many errors in the error side
Section titled “Many errors in the error side”Put a non-empty array of errors on the failure side. An empty array would mean “failed with no reason”, so the type forbids it:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }type NonEmptyArray<A> = readonly [A, ...A[]]interface FieldError { readonly field: string readonly message: string}type Validation<A> = Result<A, NonEmptyArray<FieldError>>
declare const fail: (field: string, message: string) => Validation<never>const validateSecret = (secret: string): Validation<string> => secret.length >= 8 ? { ok: true, value: secret } : fail("secret", "secret must be at least 8 characters")Each field validator looks at one value and reports at most one error. Now we need a combinator that runs them all.
struct: run all, keep all
Section titled “struct: run all, keep all”struct takes an object whose values are Validations and returns a Validation of an object with
the same keys:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }const ok = <A>(value: A): Result<A, never> => ({ ok: true, value })const err = <E>(error: E): Result<never, E> => ({ ok: false, error })type NonEmptyArray<A> = readonly [A, ...A[]]interface FieldError { readonly field: string readonly message: string}type Validation<A> = Result<A, NonEmptyArray<FieldError>>
export function struct<S extends Readonly<Record<string, Validation<unknown>>>>( shape: S,): Validation<{ readonly [K in keyof S]: S[K] extends Validation<infer A> ? A : never }>export function struct(shape: Readonly<Record<string, Validation<unknown>>>): Validation<Record<string, unknown>> { const values: Record<string, unknown> = {} const errors: FieldError[] = [] for (const [key, v] of Object.entries(shape)) { if (v.ok) values[key] = v.value else errors.push(...v.error) } const [first, ...rest] = errors return first === undefined ? ok(values) : err([first, ...rest])}The loop looks at every field, never stops, and keeps every error. The destructuring at the end
proves to the compiler that the list is non-empty. The return type is a mapped type
that unwraps each Validation<A> into A, so the success is typed field by field. A list version,
all(validations), is the same loop over an array.
Used on the form:
type Validation<A> = { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: readonly [unknown, ...unknown[]] }declare function struct<S extends Readonly<Record<string, Validation<unknown>>>>( shape: S,): Validation<{ readonly [K in keyof S]: S[K] extends Validation<infer A> ? A : never }>declare function validateName(s: string): Validation<string>declare function validateUrl(s: string): Validation<string>declare function validateRetries(n: number): Validation<number>declare const input: { readonly name: string; readonly url: string; readonly retries: number }
const fields = struct({ name: validateName(input.name), url: validateUrl(input.url), retries: validateRetries(input.retries),})// Validation<{ readonly name: string; readonly url: string; readonly retries: number }>Why this is not flatMap
Section titled “Why this is not flatMap”struct works because the fields are independent: validating url does not need the validated
name. Every validation is computed before any are combined. That is called applicative style (the
second tool next to flatMap’s monad style). flatMap lets a later step choose what to do based on
an earlier value, so it must wait for the earlier value, and so it cannot continue after a failure.
struct never lets a later step see an earlier value, so it can always continue.
A cross-field rule such as “the secret must not contain the name” does depend on values. Run it after
struct, with flatMap, so it executes only once all fields are valid:
type Result<A, E> = | { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: E }declare const ok: <A>(a: A) => Result<A, never>declare const fail: (field: string, message: string) => Result<never, readonly [{ field: string; message: string }]>declare const flatMap: <A, B, F>(f: (a: A) => Result<B, F>) => <E>(r: Result<A, E>) => Result<B, E | F>declare const fields: Result<{ readonly name: string; readonly secret: string }, readonly [{ field: string; message: string }]>
const checked = flatMap((s: { readonly name: string; readonly secret: string }) => s.secret.includes(s.name) ? fail("secret", "secret must not contain the name") : ok(s),)(fields)If a field is invalid, comparing secret against name would be comparing garbage, so skipping the
cross-field rule is correct, not a limitation.
Exercise
Section titled “Exercise”validateName, validateUrl, validateRetries and validateSecret are given. Write struct, all
and validateSource. Errors come out in field order, and the cross-field rule must run only when
every field is valid.
flatMapstops at the first failure, so it reports one error per round trip.- Put a
NonEmptyArray<FieldError>on the failure side, so “failed with no error” is not a state. structandallrun every validator and combine the successes or concatenate the errors.- Independent fields can run together. A rule that needs values from other fields waits for them with
flatMap, afterstruct. - Use this for input people can correct, and use
flatMaporgenwhere steps depend on each other.
Further reading
Section titled “Further reading”- Narrowing: discriminated unions and exhaustiveness checking.