Valibot Composable Schema Pipes

Chain validation and transformation steps with Valibot pipe syntax, from string trimming through branded IDs to parseable JSON payloads.

TypescriptForm Validation

Code

typescriptsnippet
42 lines
import * as v from 'valibot';

const Email = v.pipe(
  v.string(),
  v.trim(),
  v.toLowerCase(),
  v.nonEmpty(),
  v.email('enter a valid email'),
);

const UserId = v.pipe(
  v.string(),
  v.uuid(),
  v.brand('UserId'),
);

const JsonBody = v.pipe(
  v.string(),
  v.trim(),
  v.json('body must be valid JSON'),
  v.object({
    id: UserId,
    email: Email,
    score: v.pipe(v.number(), v.min(0), v.max(100)),
  }),
);

type UserRef = v.InferOutput<typeof JsonBody>;

const parsed = v.safeParse(JsonBody, JSON.stringify({
  id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8',
  email: '  ADA@Example.COM ',
  score: 88,
}));

if (parsed.success) {
  console.log(parsed.output.email, parsed.output.score);
} else {
  for (const issue of parsed.issues) {
    console.log(issue.path?.map((p) => p.key).join('.'), issue.message);
  }
}

How the code works

Repetition is confined to for (const issue of parsed.issues) — the rest of the file is straight-line.

The file’s state is a handful of top-level bindings: Email, UserId, JsonBody, parsed.

Points of care

  • Plan for an install step: valibot is a real dependency, resolved by the package manager.

Statements that matter

const parsed = v.safeParse(JsonBody, JSON.stringify({
id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8',
email: '  ADA@Example.COM ',
score: 88,
}));

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`valibot` — install it with the package manager before running.