I have two fields name
and preview
. I have done validation for these fields (code below), but an error is returned to me when I add a file to the preview
(error that I have to fill in this field)
const validationSchema = Yup.object().shape({
name: Yup.string().required('Enter name'),
preview: Yup.mixed().test('required', 'You need to provide a file', (file) => {
if (file) return true
return false
}),
})
interface AddCategoryProps {}
export default function AddCategory({}: AddCategoryProps) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
defaultValues: {},
mode: 'onChange',
resolver: yupResolver(validationSchema),
})
const onSubmit = handleSubmit(({ name, preview }) => {
console.log({ name, preview })
})
return (
<section className={styles.wrapper}>
<form onSubmit={onSubmit} className={styles.form}>
<AdminFormInput
register={register}
registerName='name'
errorText={errors.name?.message}
isError={Boolean(errors.name?.message)}
label='Name'
/>
<AdminFormInput
register={register}
registerName='preview'
errorText={errors.preview?.message}
isError={Boolean(errors.preview?.message)}
label='Preview'
isFile={true}
previewText='Select file'
/>
<AdminFormButton />
</form>
</section>
)
}
// AdminFormInput //
import { useRef } from 'react'
import styles from './AdminFormInput.module.sass'
import { FieldValues, Path, UseFormRegister } from 'react-hook-form'
interface AdminFormInputProps<T extends FieldValues> {
label: string
isFile?: boolean
previewText?: string
isSelect?: boolean
registerName: Path<T>
register: UseFormRegister<T>
isError: boolean
errorText: string | undefined
}
export const AdminFormInput = <T extends FieldValues>({
label,
isFile,
previewText,
isSelect,
registerName,
register,
isError,
errorText,
}: AdminFormInputProps<T>) => {
const fileRef = useRef<any>()
return (
<div className={styles.wrapper}>
<label className={styles.title}>{label}</label>
{!isFile && !isSelect && (
<>
<input {...register(registerName)} type='text' className={styles.input} />
{isError && <span className={styles.error}>{errorText}</span>}
</>
)}
{isFile && (
<>
<input
{...register(registerName)}
type='file'
accept='image/png, image/gif, image/jpeg'
hidden
ref={fileRef}
/>
<div className={styles.file} onClick={() => fileRef.current.click()}>
{previewText}
</div>
{isError && <span className={styles.error}>{errorText}</span>}
</>
)}
</div>
)
}
export default AdminFormInput
I tried to do this, but when I click on the submit button of the form, the name
field is filled in, but the preview field remains undefined
const validationSchema = Yup.object().shape({
name: Yup.string().required('Введите название категории'),
preview: Yup.mixed()
}),
})
Actually, the problem is that the preview
field does not include the file that I select