import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
interface MyFormType {
image: FileList | null;
}
const defaultValues: MyFormType = {
image: null,
};
const validationSchema:yup.ObjectSchema<MyFormType> = yup.object({
image: yup.mixed<FileList|null>().nullable()
});
const MyForm: React.FC = () => {
const { register, handleSubmit, formState: { errors } } = useForm<MyFormType>({
resolver: yupResolver(validationSchema),
});
const onSubmit = (data: MyFormType) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>
Image:
<input type="file" {...register("image")} />
{errors.image && <p>{errors.image.message}</p>}
</label>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
I have tried everything I could. I need to upload and image and validate it using yup. I am new to typescript.
I have tried chatgpt and gemini. I am unable to find any example.
New contributor
lakhiwaladev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.