Reputation: 1
I'm new to Formik, can anyone tell me how to upload multiple files with validation. using Formik and Yup.
Upvotes: 0
Views: 1693
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:-
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