I am using react hook form to upload a file, and my file upload field is:
<input
className={`form-control ${
errors["cover_image"] ? "border-red-500" : ""
}`}
type="file"
id="cover_image"
{...register("cover_image")}
onChange={handleChange}
/>
and I have yup validation as:
cover_image: Yup.mixed()
.test("name", "Cover Image is required", (value) => {
return value[0] && value[0].name !== "";
})
.test("fileSize", "File must be less than 2MB", (value) => {
return value[0] && value[0].size <= 2000000;
})
.test("type", "Only image are supported", (value) => {
return value[0] && value[0].type.includes("image");
}),
It is working fine in the case of creating a page, it shows required, when not uploaded, but in the case of the edit page, it is showing a field is required, if I don't upload any file. There is a file value on item.cover_image.
I have also tried defaultValue={item.cover_image}, but it is not allowing to set me default value in case of edit. How would be the best way to handle this situation?
Instead of using an external package to validate I would recommend using validation of react-hook-form
import { useForm } from 'react-hook-form'
export default function App() {
const { register, handleSubmit, formState } = useForm()
console.log({ errors: formState.errors })
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<input
type="file"
{...register('cover_image', {
validate: value => {
const isExists = !!value.length
const isGoodSize = value[0] && value[0].size <= 2000000
const isImageType = value[0] && value[0].type.includes('image')
if (!isExists) return "Cover Image is required"
if (!isGoodSize) return 'File must be less than 2MB'
if (!isImageType) return 'Only image are supported'
return undefined
}
})}
/>
<input type="submit" />
</form>
)
}