CSS dimensions
Validate values such as 12px, 1.5rem, or 100% by combining a numeric schema with an enum of permitted units.
Zod · Module
z.templateLiteral creates a Zod schema for strings formed by concatenating literal text and compatible schemas. It validates the complete assembled value and infers a corresponding TypeScript template-literal type.
z.templateLiteral builds a schema for strings assembled from literal text and compatible Zod schemas. It combines the accepted patterns of each component, so the resulting validator checks the complete concatenated string while preserving the corresponding template-literal type.
z.templateLiteral([literalOrSchema, ...])| Name | Type | Description |
|---|---|---|
parts | array | An array of literal strings and Zod schemas whose inferred types are assignable to string, number, bigint, boolean, null, or undefined. |
A Zod schema representing the concatenated template-literal pattern.
import { z } from "zod";
const cssLength = z.templateLiteral([
z.number(),
z.enum(["px", "em", "rem"]),
]);
cssLength.parse("12px"); // "12px"
// cssLength.parse("12pt"); // throws
This schema accepts a number followed by one of the specified CSS units.
Validate values such as 12px, 1.5rem, or 100% by combining a numeric schema with an enum of permitted units.
Model structured identifiers with fixed prefixes, separators, and constrained dynamic sections.
Represent TypeScript template-literal types that ordinary string schemas cannot express.
Pass an array containing literal strings and compatible Zod schemas. Zod combines their patterns into one validator for the concatenated string.
Follow-up: Which component types are allowed? Any schema whose inferred type is assignable to string, number, bigint, boolean, null, or undefined.
The resulting type follows the template structure, such as ${number}px for a number schema followed by the literal "px". Parsing validates the entire assembled value.
Follow-up: Can a finite set of suffixes be modeled? Yes; use an enum schema, such as z.enum(["px", "em", "rem"]), after the numeric component.
Zod uses the internal regular-expression representation of stringifiable schemas and concatenates those patterns into a super-regex. This means supported formats and constraints represented there participate in validation.
Follow-up: Do refinements participate too? No; the documentation specifically excludes custom refinements from this mechanism.
z.string()z.literal()z.number()z.enum()z.nullable()