How to validate mulitple images and video upload using formik and yup in react js

Viewed 25

I need help in validating multiple images using formik and yup. I want the user to be able to upload multiple images and then use formik and yup to validate the image size and type and also make sure that the user uploads at least 1 image. Same thing for video uploads too. I also want the user to be able to preview the image and videos before submitting the form. I got single image upload to work using formik and yup but I can't seem to get multiple images to work. Here is my code:

const SUPPORTED_FORMATS = ["image/jpg", "image/png", "image/jpeg"];
const VIDEO__SUPPORTED__FORMATS = ["video/mp4", "video/x-m4v", "video/*"];

const validationSchema = Yup.object({
  multipleImages:
    Yup.mixed().required("Please select an image of the house for upload")
      .test("FILE_SIZE", "File size is too big", (value) => {
        if (value && value?.length > 0) {
          for (let i = 0; i < value.length; i++) {
            if (value[i].size > 5242880) {
              return false;
            }
          }
        }
        return true;
      })
      .test("FILE_TYPE", "Invalid file format selected", (value) => {    
        if(value && value.length > 0) {
          for (let i = 0; i < value.length; i++){
            if (value[i].type !== "image/png" && value[i].type !== "image/jpg" && value[i].type !== "image/jpeg") {
              return false;
            }
          }
        
        }
        return true;
      }),
  singleImage:
    Yup.mixed().required("Please select an image of yourself for upload")
      .test("FILE_SIZE", "File size is too big", (value) => value && value.size < 1024 * 1024 * 1024 * 1024 * 1024)
      .test("FILE_TYPE", "Invalid file format selected", (value) => value && SUPPORTED_FORMATS.includes(value.type)),
  video:
    Yup.mixed().required("Please select a video of the house for upload")
      .test("FILE_SIZE", "File size is too big", (value) => value && value.size < 1024 ^ 150)
      .test("FILE_TYPE", "Invalid file format selected", (value) => value && VIDEO__SUPPORTED__FORMATS.includes(value.type)),
});
0 Answers
Related