Trasformare e perfezionare i dati con Zod
Vada oltre la validazione di base trasformando i valori analizzati e aggiungendo regole di refinement personalizzate con Zod.
Trasformare e perfezionare i dati con Zod è una lezione tRPC End-to-End Type Safe APIs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento tRPC End-to-End Type Safe APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Beyond Pass/Fail
Zod does more than accept or reject data. It can transform valid input into a cleaner shape and apply custom rules that built-in validators cannot express.
The transform Method
.transform() changes a value after it passes validation, producing a new output type.
const trimmed = z.string().transform((s) => s.trim());
trimmed.parse(" hi "); // "hi"Coercing Types
Zod can coerce inputs, useful for query strings that arrive as text but should be numbers.
const page = z.coerce.number().int().positive();
page.parse("5"); // 5 as a numberDefault Values
Provide a fallback when a field is missing.
const schema = z.object({
limit: z.number().default(20),
});
schema.parse({}); // { limit: 20 }Custom Refinements
.refine() adds a custom boolean check with a message when it fails.
const password = z.string().refine(
(val) => val.length >= 8,
{ message: "Too short" }
);Cross-Field Validation
Refine an object to compare two fields, like confirming a password.
const form = z.object({
pw: z.string(),
confirm: z.string(),
}).refine((d) => d.pw === d.confirm, {
message: "Passwords must match",
path: ["confirm"],
});superRefine for Multiple Errors
.superRefine() lets you push several issues in one pass for richer validation.
const s = z.string().superRefine((val, ctx) => {
if (!/[A-Z]/.test(val)) ctx.addIssue({ code: "custom", message: "Need uppercase" });
if (!/[0-9]/.test(val)) ctx.addIssue({ code: "custom", message: "Need digit" });
});Chaining Transforms
Validation and transformation chain in order.
const slug = z.string()
.min(1)
.transform((s) => s.toLowerCase().replace(/\s+/g, "-"));
slug.parse("Hello World"); // "hello-world"Input vs Output Types
After a transform, the input type and output type differ. Use z.input and z.output to read each.
type In = z.input<typeof page>; // string | number
type Out = z.output<typeof page>; // numberSafe Parsing
Use safeParse to get a result object instead of throwing, ideal for handling errors gracefully.
const r = password.safeParse("short");
if (!r.success) console.log(r.error.issues);Pipe for Validate-then-Transform
Use .pipe() to first coerce or transform a value and then run further validation on the result.
const id = z.string().transform(Number).pipe(z.number().int());Quick Check
Test your Zod knowledge.
Recap
You leveled up your Zod schemas:
- transform and coerce reshape valid data
- refine / superRefine add custom and cross-field rules
- safeParse handles errors without throwing
These tools turn Zod into a powerful data shaping and validation layer.
Impara tRPC End-to-End Type Safe APIs con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 10
- Lezioni
- 40
Domande Frequenti
La lezione «Trasformare e perfezionare i dati con Zod» è gratuita?
Sì — il testo completo di «Trasformare e perfezionare i dati con Zod» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso tRPC End-to-End Type Safe APIs, passa a CoddyKit PRO. Il corso tRPC End-to-End Type Safe APIs include 4 lezioni in totale.
Cosa imparerò in «Trasformare e perfezionare i dati con Zod»?
Vada oltre la validazione di base trasformando i valori analizzati e aggiungendo regole di refinement personalizzate con Zod. Eserciti tRPC End-to-End Type Safe APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare tRPC End-to-End Type Safe APIs?
Non è richiesta alcuna esperienza precedente. tRPC End-to-End Type Safe APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Trasformare e perfezionare i dati con Zod»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione tRPC End-to-End Type Safe APIs?
Sì. Ogni lezione tRPC End-to-End Type Safe APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Introduzione agli schemi Zod
- Definire schemi Zod complessi
- Integrare Zod nelle procedure tRPC
- Trasformare e perfezionare i dati con Zod