'How to create a type for file type `Record<string, File>` in zod
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);
}}
/>
)
}
Solution 1:[1]
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);
}}
/>
Solution 2:[2]
Maybe z.instanceof
can solve it?
If you want to validate the File type ...
z.instanceof (File)
Or, for FileList type...
z.instanceof (FileList)
Solution 3:[3]
zodSchema:
file:
typeof window === "undefined"
? z.string()
: record(any()).nullable(),
initialValues:
file: "undefined",
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Samat Zhetibaev |
Solution 2 | |
Solution 3 |