Validate before transforming
A string must be checked before being converted to its character count.
Zod · Module
z.pipe() composes schemas into a sequential pipeline. It is especially useful for validating data before a transform and validating or processing the transformed result.
z.pipe(first, second) creates a pipeline that parses input with the first schema and passes that result into the second schema. In the common transform pattern, the input is validated before transformation, and the transformed value can then be validated or further processed by the next schema.
z.pipe(firstSchema, secondSchema)
schema.pipe(secondSchema)| Name | Type | Description |
|---|---|---|
first | ZodType | The schema that parses the original input first. |
second | ZodType | The schema that receives the first schema's parsed output. |
A pipe schema representing the composed input and output schemas; in the instance API, this is a ZodPipe.
.pipe() after the first schema and accepts the next schema as its argument.import { z } from "zod";
const stringToLength = z.string().pipe(z.transform((value) => value.length));
console.log(stringToLength.parse("hello")); // 5The first schema validates the string, then the transform converts it to its length.
A string must be checked before being converted to its character count.
A transformation produces a value that needs another schema's constraints.
A schema has distinct input and output types and both boundaries matter.
A pipe composes two schemas in sequence. The input is parsed by the first schema, and that parsed result is passed to the second schema.
Follow-up: What happens when encoding a codec-based pipe? Encoding reverses the order: the value is encoded with the second schema first, then passed into the first.
Pipes are especially useful with transforms. They let you validate an input before changing it, or validate the transformed result with another schema.
Follow-up: How would you inspect the two type boundaries? Use the input and output type utilities, which correspond to the pipe's input and output sides.
The Zod API uses the instance method schema.pipe(nextSchema). It returns a pipeline schema that can be parsed like other Zod schemas.
Follow-up: What is the Zod Mini equivalent? Use the functional form z.pipe(firstSchema, secondSchema) and parse with z.parse.
z.transformz.inputz.outputZodPipe