All topics
Formsintermediate

Schema Validation with Zod/Yup

Learn how declarative schema validation libraries define and enforce data shape and constraints for form inputs.

Schema validation libraries like Zod and Yup let you describe the expected shape and constraints of form data declaratively — types, required fields, string length, number ranges, custom refinements — as a single schema object, rather than writing imperative if-statements to check each field manually. The schema itself becomes the single source of truth for what 'valid' means for that form.

A validation schema is like a customs inspection checklist that clearly states every requirement a shipment must meet before crossing the border — instead of an inspector improvising checks case by case, everyone (the code and, in Zod's case, the type system) reads from the exact same written rulebook.

Key Concepts

1
Zod is TypeScript-first, designed so that a schema's inferred TypeScript type (z.infer<typeof schema>) stays perfectly in sync with the validation rules — defining validation once gives you both runtime checks and compile-time types, avoiding the common problem of type definitions and validation logic drifting apart over time. Yup has a similar API and long-standing integration with Formik, though it's less tightly coupled to TypeScript's type inference.
z.infer<typeof schema>
2
Both libraries integrate with form libraries (React Hook Form via a resolver adapter for Zod, or validationSchema for Formik with Yup) so that validation runs automatically as part of the form's submit and per-field validation flow, and both produce structured error objects that map cleanly to which specific field(s) failed and why, useful for displaying inline error messages.
validationSchema
3
Interviewers ask candidates to design a schema for a realistic form (like a signup form with password confirmation matching) and to explain the benefit of centralizing validation rules in a schema versus scattering ad hoc validation checks throughout form-handling code, particularly the type-safety benefit Zod provides in a TypeScript codebase.