Skip to content

Instantly share code, notes, and snippets.

@bryanltobing
Last active September 14, 2024 15:03
Show Gist options
  • Save bryanltobing/443f2c417b4ed537284be7cf55bf10ad to your computer and use it in GitHub Desktop.
Save bryanltobing/443f2c417b4ed537284be7cf55bf10ad to your computer and use it in GitHub Desktop.
Zod schema to validate input type file
import { z } from "zod"
const schema = z.object({
file:
typeof window === "undefined" // this is required if your app rendered in server side, otherwise just remove the ternary condition
? z.undefined()
: z
.instanceof(FileList)
.refine(file => file.length !== 0, {
message: "File is required",
})
.refine(
file => {
const fileType = file.item?.(0)?.type || "";
return fileType === "image/png";
},
{
message: "File must be in .png format",
}
)
.refine(
file => {
const fileSize = file.item?.(0)?.size || 0;
return fileSize <= 200000;
},
{ message: "File size must be less than or equal to 200kb" }
),
})
@melodyclue
Copy link

melodyclue commented Nov 16, 2022

I think File is not defined is shown on NextJS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment