7

I use input type="file" and instead of saving data in FileData I use just plain object and created a type for it: Record<string, File>. It works well, but when I try to create a validator with zod – I don't get how to create the same type for it.

The usage:

import { object as zodObject, string, number } from 'zod';
import { useValidators } from '../some';

const useValidation = () => {
  const { createResolver } = useValidators();
  
  return {
    resolver: createResolver(
      zodObject({
        name: string(),
        price: number(),
        files: ???,  
      })
    ),
  };
}; 

The doc is quite excessive, but I could not find any example for my case: https://github.com/colinhacks/zod

The usage of input:


const App = () => {
  const [files, setFiles] = useState<Record<string, File>>({}); 

  return (
    <input 
      type="file" 
      onChange={event => {
        const files = event.target.files;
        const newFiles: Record<string, File> = {};
        const keys = Object.keys(files);
        
        for(let i = 0; i < keys.length; i++) {
          const file = newFiles[key];
          newFiles[file.name] = file;
        }

        setFiles(newFiles);
      }}
    />

  )

}

2
  • How is your File type looks like?
    – nemesv
    Dec 20, 2021 at 11:42
  • @nemesv, I have added a simple example of usage input. So, the main case to have this type to set file.name as a key of object to have a fast access for updating and deleting files. Cause input should store multiple files and user can add or remove some of the files. Dec 20, 2021 at 11:50

4 Answers 4

9

Maybe z.instanceof can solve it?

If you want to validate the File type ...

z.instanceof (File)

Or, for FileList type...

z.instanceof (FileList)


https://github.com/colinhacks/zod/issues/387

3
  • This is the correct answer. Also, another way of defining your schemas is to just import { z } from "zod" instead of importing zod methods individually
    – CRIS
    Apr 26, 2022 at 17:22
  • If you get a an error about File not being a valid reference, use z.custom<File>(). Apr 11 at 10:04
  • 2
    @TomášHübelbauer as the doc suggests, z.custom<File>() will perform no validation. We need to pass a validation function to this and the code might look like z.custom<File>((file) => file instanceof File)
    – Pratik Dev
    Aug 18 at 13:31
0

try this:

    z.object({
        file: z
         .any()
         .refine((files) => files?.length == 1, "File is required.")  
    })

and then use other file properties in refine to filter it as u need like:

  • files?.[0]?.size
  • files?.[0]?.type
-2

My colleague has found the solution:

// useValidation file
import { object as zodObject, string, number, record, any } from 'zod';
import { useValidators } from '../some';

const useValidation = () => {
  const { createResolver } = useValidators();
  
  return {
    resolver: createResolver(
      zodObject({
        name: string(),
        price: number(),
        files: record(any()).nullable(),  
      })
    ),
  };
};  

And in the file that uses object with file data we use it in this way:

// fileInput on `onRemove` action return `fileName: string` and my file object looks like this:  { fileName: File } 

const [files, setFiles] = useState<Record<string, File> | null>(null);

<FileInput 
  onChange={(fileName) => {
    const updatedFiles = { ...files as Record<string, File> }; 
    delete updatedFiles[fileName];
    setFiles(updatedFiles);
  }}
/>
-2

zodSchema:

  file:
    typeof window === "undefined"
      ? z.string()
      : record(any()).nullable(),

initialValues:

file: "undefined",

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.