Question

Validating file presence with YUP

I'm using Yup to validate my form. In one of my form, I want to validate that one <input type="file" /> has a file.

I've tested this (and it's not working):

Yup.object().shape({
  file: Yup.object().shape({
    name: Yup.string().required()
}).required('File required')

I've the following error message in the console:

file must be a object type, but the final value was: null (cast from the value {}). If "null" is intended as an empty value be sure to mark the schema as .nullable()

Any idea?

 46  85309  46
1 Jan 1970

Solution

 33

Here is how I did it

import { object, string, mixed } from "yup"

const schema = object().shape({
  attachment: mixed().test("fileSize", "The file is too large", (value) => {
    if (!value.length) return true // attachment is optional
    return value[0].size <= 2000000
  }),
})
2020-07-31

Solution

 28

I solved it like this:

const schema = Yup.object().shape({
    file: Yup.mixed().required('File is required'),
})

It throws an error if you attempt to submit the form without a file, and the error goes away when you have a file.

2021-08-04