I'm building a NextJS15 Form with useForm() hook and Zod validation that includes a file Input. Unfortunately, when I try to submit the form, Zod considers the uploaded file as a String (C:\FakePath\File.jpg) instead of considering a File object.
As long as the form is not submitted, I checked that form.getValues('media') is an instance of File, and it is.
But when I hit the submit button, Zod throws an error saying that 'media' is not an instance of File.
See the bits of code below :
const formSchema = z.object({
...,
media: z.instanceof(File).optional().nullable(),
...,
})
export default function QuizForm() {
const handleImageUpload = (event, index) => {
const file = event.target.files[0]
if (file) {
form.setValue(`questions.${index}.media`, file);
}
}
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
...,
media: null,
...,
}
})
async function onSubmit() {
const formData = form.getValues()
formData.questions.map((question, index) => {
console.log(question.media) // This outputs C:\\FakePath\\File.jpg
})
}
// File Input Component
<Input
type="file"
accept="image/*"
onChange={(e) => {
handleImageUpload(e, index);
field.onChange(e);
}}
/>
}
I'd like some explanation on this and maybe a solution because AI prompting didn't get me out of this issue ;)
Thanks !