Last active
September 14, 2024 15:03
-
-
Save bryanltobing/443f2c417b4ed537284be7cf55bf10ad to your computer and use it in GitHub Desktop.
Zod schema to validate input type file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" } | |
), | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
File is not defined
is shown on NextJS.