I try to make file input validation using React Hook Form and Yup. I wrote the code below but when I am testing the size of file it shows me here console.log(value[0].size); that the value is undefined even if I selected a file in file input. What is wrong with it?
I am using FormProvider and useFormContext.
In my Parent.js I have this code:
const Parent = () => {
const addingProcess = () => {
//..
};
const validationSchema = Yup.object().shape({
photo: Yup.mixed()
.required("You need to provide a file")
.test("fileSize", "File Size is too large", (value) => {
console.log(value[0].size);
return value[0].size <= 5242880;
})
.test("fileType", "Unsupported File Format", (value) =>
["image/jpeg", "image/png", "image/jpg"].includes(value.type)
),
});
const methods = useForm({
mode: "onSubmit",
resolver: yupResolver(validationSchema),
});
const { handleSubmit } = methods;
return (
<Wrapper>
<FormProvider {...methods}>
<Form onSubmit={handleSubmit(addingProcess)}>
<Photos />
</Form>
</FormProvider>
</Wrapper>
);
};
In my Photos.js I have:
const Photos = () => {
return (
<Wrapper>
<PhotoHolder/>
</Wrapper>
);
};
export default Photos;
In my PhotoHolder.js file I have this (yes, I need to have the onChange like this):
const PhotoHolder = () => {
const { register } = useFormContext();
const validator = register("photo");
return (
<Input
name="photo"
type="file"
multiple
onChange={(e) => {
validator.onChange(e);
}}
/>
);
};