0

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.

Zod Error

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 !

2
  • Does your form have the proper enctype set? Commented May 23 at 7:16
  • Yes, my form has encType="multipart/form-data" Commented May 23 at 21:52

1 Answer 1

0

Problem is solved !

I needed to add the property ref={field.ref} to the <Input />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.