Reputation: 1363
I want to validate file input if a file is selected, I found the solution for Formik/Yup but it validates even if file is not selected.
avatar: Yup.mixed()
.test("fileSize", "File is too large", value => {
return value && value.size <= FILE_SIZE;
})
.test(
"fileFormat",
"Unsupported Format",
value => value && SUPPORTED_FORMATS.includes(value.type)
)
It triggers validation when I type in other inputs, I want to trigger it only if file is there since avatar is optional!
Upvotes: 2
Views: 5553
Reputation: 323
The problem is that the test is returning true
(meaning it validates) only when value
exists. You have to add a condition to accept value when it doesn't exist (ie: is null
or undefined
).
I had the exact same problem and I solved like this:
avatar: Yup.mixed()
.test(
"fileSize",
"File is too large",
value => !value || (value && value.size <= FILE_SIZE)
)
.test(
"fileFormat",
"Unsupported Format",
value => !value || (value => value && SUPPORTED_FORMATS.includes(value.type))
)
Upvotes: 3