Capítulo 10 de 61

Chapter 10: Dates

Core Idea

z.date() validates actual Date instances — it does not parse date strings; that's the job of the ISO string formats or a codec.

Key Concepts

  • z.date(): passes only real Date objects; a valid ISO string input fails (z.date().safeParse("2022-01-12T06:15:00.000Z")success: false).
  • .min() / .max(): bound the date to a range, each taking a Date instance.
  • Custom error via error callback: z.date({ error: issue => ... }) lets the message differ based on whether the input was undefined (missing) vs. present-but-invalid.

Code Examples

z.date().safeParse(new Date()); // success: true
z.date().safeParse("2022-01-12T06:15:00.000Z"); // success: false

z.date().min(new Date("1900-01-01"), { error: "Too old!" });
z.date().max(new Date(), { error: "Too young!" });

z.date({
  error: issue => issue.input === undefined ? "Required" : "Invalid date"
});
  • What it demonstrates: z.date() is strict about the type being a Date, with range checks and a per-issue custom error message.

Anti-patterns

  • Passing an ISO date string to z.date() expecting it to parse: it won't — z.date() validates that the value already is a Date instance. To accept an ISO string and produce a Date, use a codec (z.codec) or z.iso.datetime().pipe(z.transform(v => new Date(v))).

Key Takeaways

  1. z.date() is a type check, not a parser — convert strings to Date objects before or via a pipe/codec, not by relying on z.date() to do it.
  2. Range checks (.min()/.max()) take real Date instances, so compute the bound (e.g. new Date()) at schema-definition or parse time as appropriate.
  3. The error callback receives the issue, letting you distinguish "missing" from "wrong type/out of range" in the message.

Connects To

  • ISO Dates (String Formats): for validating date/time strings before converting them to Date objects.
  • Codecs: the idiomatic way to go from an ISO string input to a Date output.