Last active
September 7, 2024 16:34
-
-
Save Edlavio/47b5d449a266cd6efbcec6322d6006e5 to your computer and use it in GitHub Desktop.
Image validation using Zod
This file contains hidden or 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 MAX_FILE_SIZE = 1024 * 1024 * 1; | |
const ACCEPTED_IMAGE_MIME_TYPES = [ | |
'image/jpeg', | |
'image/jpg', | |
'image/png', | |
]; | |
export const imageSchema = z.object({ | |
image: z | |
.any() | |
.optional() | |
.refine((files) => { | |
if (!files || !files[0]) return true; | |
return files[0].size <= MAX_FILE_SIZE; | |
}, `The max size is 1MB.`) | |
.refine((files) => { | |
if (!files || !files[0]) return true; | |
return ACCEPTED_IMAGE_MIME_TYPES.includes(files[0].type); | |
}, 'Only .jpg, .jpeg, .png are supported.'), | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment