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: ' [email protected] ',
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);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.