Validating File using React-Hook-Form and Yup (<x> must be a `object` type, but the final value was: `null`)
Asked Answered
W

3

7

I'm working on a simple file upload form using react-hook-form and I need to validate that a file has been selected for upload. Using yup for validation. I realize there are other questions on this topic but I was unable to find a working solution.

My file upload component is based (almost 100% the same) on this answer https://mcmap.net/q/981544/-how-to-use-react-dropzone-with-react-hook-form. It seems to be working just fine, if I disable validation the file is uploaded correctly.

The issue I'm facing is when validating whether a file has been selected I get the error file must be a 'object' type, but the final value was: 'null'.

Here's a CodeSandbox showing the problem. I added some prints showing the contents of the "file" form property and its type (which shows as object)

Wormy answered 19/2, 2022 at 21:53 Comment(0)
T
12

Use schema validation below, it should work as expected.

 const fileFormSchema = yup.object().shape({
    file: mixed()
          .test("required", "You need to provide a file", (file) => {
            // return file && file.size <-- u can use this if you don't want to allow empty files to be uploaded;
            if (file) return true;
            return false;
          })
          .test("fileSize", "The file is too large", (file) => {
            //if u want to allow only certain file sizes
            return file && file.size <= 2000000;
          })
      });
Talton answered 19/2, 2022 at 23:25 Comment(2)
I think you need to include yup here: file: yup.mixed() otherwise mixed() is undefined..Juliannajulianne
Im allways getting File as undefinedObannon
C
1

This is another solution for the new version 7

 const fileSchema = yup.object().shape({
     file: yup.mixed().test("file", "You need to provide a file", (value) => {
       if (value.length > 0) {  
         return true;
       }
       return false;
       }),
   });
Coir answered 26/8, 2022 at 11:38 Comment(0)
G
0

If you're using Typescript you'll need to set the type(s):

import { ObjectSchema, mixed, object } from 'yup';

export type Schema = {
  file: File;
};

export const schema: ObjectSchema<Schema> = object<Schema>().shape({
  file: mixed<File>()
    .test('required', 'You need to provide a file', (file) => {
      if (file) {
        return true;
      }
      return false;
    })
    .required(),
});

Galwegian answered 22/5 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.