Valibot Composable Schema Pipes
Chain validation and transformation steps with Valibot pipe syntax, from string trimming through branded IDs to parseable JSON payloads.
Code
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:
valibotis 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Are there third-party dependencies?
- `valibot` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.