Skip to content

Instantly share code, notes, and snippets.

@Edlavio
Last active September 7, 2024 16:34
Show Gist options
  • Save Edlavio/47b5d449a266cd6efbcec6322d6006e5 to your computer and use it in GitHub Desktop.
Save Edlavio/47b5d449a266cd6efbcec6322d6006e5 to your computer and use it in GitHub Desktop.
Image validation using Zod
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