DEV Community

Prodipta Banerjee
Prodipta Banerjee

Posted on • Edited on

Validate file with ZOD

Zod is a TypeScript-first schema validation library with static type inference. You can create validation schemas for either field-level validation or form-level validation1. Hereโ€™s an example of how you can use Zod for schema validation for a file:

// Max size is 5MB.
const MAX_FILE_SIZE = 5000000; 

function checkFileType(file: File) {
    if (file?.name) {
        const fileType = file.name.split(".").pop();
        if (fileType === "docx" || fileType === "pdf") return true;
    }
    return false;
}

export const fileSchema = z.object({
z.any()
.refine((file: File) => file?.length !== 0, "File is required")
.refine((file) => file.size < MAX_FILE_SIZE, "Max size is 5MB.")
.refine((file) => checkFileType(file), "Only .pdf, .docx formats are supported."),`
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)