File input validation using React Hook Form and Yup

Viewed 4352

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);
    }}
    />
  );
};
1 Answers

I think you can use the function useControl with render like this:

<Controller
    control={control}
    name="photo"
    render={({ field: { onChange, onBlur, value, ref } }) => (
      <Photos
        onBlur={onBlur}
        value={value}
        onChange={onChange}
        {...field}
      />
    )}
  />

By this method we can validate custom input, the key concept here is we have to pass control object and and and field into custom input component.

For more information you can visit this documentation https://react-hook-form.com/api/usecontroller/controller

Related