Capítulo 23 de 61

Chapter 23: Files

Core Idea

z.file() validates actual File instances (e.g. from a browser file input), with size and MIME-type constraints.

Key Concepts

  • z.file(): base schema for File instances.
  • .min(bytes) / .max(bytes): bound the file's .size property.
  • .mime(type) / .mime([type, ...]): restrict to one or more MIME types.
  • z.promise() is deprecated: there are almost no valid use cases for a Promise schema — await the value before parsing it with Zod instead of trying to validate a Promise itself.

Code Examples

const fileSchema = z.file();
fileSchema.min(10_000);     // minimum size in bytes
fileSchema.max(1_000_000);  // maximum size in bytes
fileSchema.mime(["image/png", "image/jpeg"]);
  • What it demonstrates: chaining size and MIME-type constraints onto a base z.file() schema.

Anti-patterns

  • Using z.promise(): deprecated — resolve the promise (await) before validating its resolved value with Zod, rather than validating the Promise wrapper itself.

Key Takeaways

  1. z.file() is for validating real File objects (upload inputs), constrained by size and MIME type — it doesn't parse file contents.
  2. Don't reach for z.promise() — it's deprecated; validate the awaited, resolved value instead.

Connects To

  • Strings: File validation is often paired with string schemas for filename/metadata fields in the same form.