Typed Multipart FormData Validation

Validate multipart FormData uploads with a Zod file schema, checking kind, size, and required metadata before persisting any file.

TypescriptFile Upload

Code

typescriptsnippet
52 lines
import { z } from 'zod';

const MAX_FILE_BYTES = 5 * 1024 * 1024;

const FileSchema = z.instanceof(File)
  .refine((f) => f.size <= MAX_FILE_BYTES, {
    message: 'file exceeds 5MB limit',
  })
  .refine(
    (f) => ['image/png', 'image/jpeg'].includes(f.type),
    { message: 'only png or jpeg accepted' },
  );

const UploadSchema = z.object({
  avatar: FileSchema,
  displayName: z.string().min(2).max(40),
  consent: z.literal('on'),
});

type UploadInput = z.infer<typeof UploadSchema>;

async function handleAvatarForm(form: FormData) {
  const raw: Record<string, unknown> = {};

  for (const [key, value] of form.entries()) {
    if (value instanceof File && value.size === 0 && value.name === '') {
      continue;
    }
    raw[key] = value;
  }

  const parsed = UploadSchema.safeParse(raw);
  if (!parsed.success) {
    return {
      ok: false as const,
      issues: parsed.error.issues.map((i) => ({
        field: i.path.join('.'),
        message: i.message,
      })),
    };
  }

  const input: UploadInput = parsed.data;
  const bytes = new Uint8Array(await input.avatar.arrayBuffer());
  await persistAvatar(input.displayName, bytes);

  return { ok: true as const, name: input.avatar.name, size: bytes.length };
}

async function persistAvatar(_name: string, _bytes: Uint8Array) {
  console.log('persisting avatar');
}

What the code does

Typed Multipart FormData Validation reduces to the functions handleAvatarForm and persistAvatar.

Iteration happens inside for (const [key, value] of form.entries()) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Reach for zod and what you get is z — that is the whole API contact area.

The result comes back as an object carrying const, name.

Caveats

  • Dependency check: zod — not built-in, must be present in the project.
  • The guard value instanceof File && value.size === 0 && value.name === '' short-circuits the flow with an early continue when its condition holds.

Applying it

The main signature reads async function handleAvatarForm(form: FormData)

Running the file prints labeled results such as persisting avatar — each operation’s effect is visible in the output.

The call returns const, name — destructure what you need at the call site.

Statements that matter

return { ok: true as const, name: input.avatar.name, size: bytes.length };
const bytes = new Uint8Array(await input.avatar.arrayBuffer());
await persistAvatar(input.displayName, bytes);

Interactive Tools for This Topic

FAQ

Does `handleAvatarForm` modify its input?
No mutation happens — the function reads its input and returns a new value.
Does this require external packages?
Yes — `zod`. Add it to your project before running the snippet.