1
votes

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!

1
Can you share code sandbox? Formik does not support file upload, so which method you used?Dani Vijay
And did you tried notRequired() ?Dani Vijay

1 Answers

2
votes

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))
  )