Tabish Adnan
Tabish Adnan

Reputation: 1

Formik & Yup | Multiple files upload validation

I'm new to Formik, can anyone tell me how to upload multiple files with validation. using Formik and Yup.

Upvotes: 0

Views: 1693

Answers (1)

Aanchal
Aanchal

Reputation: 11

I recently got this issue while I needed to validate multiple files which I was getting through the following

<input type='file' multiple accept='image/png, image/jpg, image/jpeg' onChange={(e) => { PhotoChange(e) }}
>

and found the solution as follows, hope it helps you too.

  attachment: Yup
     .mixed()
       .test("fileSize", "File Size is too large", (value) => {
         if(value && value?.length>0){
           for (let i=0;i<value.length;i++){
            if(value[i].size>5242880){
              return false;
            }
           }
        }
        return true;
       })
       .test("fileType", "Unsupported File Format", (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;
      }
       ),

Explanation:

Here, the .test is used for the following requirements:-

  1. if we want to check the size of all the files
  2. if we want to check the file type of all the files

We are simply using if and for conditions inside. If the file is null or doesn't match the size criteria or doesn't match the type criteria, then return FALSE (exiting the loop immediately) else return TRUE.

Upvotes: 1

Related Questions