I am trying to do the validation using yup for image file, what I found was https://github.com/formium/formik/issues/926 which only validates the size and also the file type.
and this one is the current yup validation that I use
file: lazy(value => {
    switch (typeof value) {
      case 'string':
        return string().required(errorHandler.requiredFile());
      default:
        return mixed()
          .required(errorHandler.requiredFile())
          .test(
            'fileSize',
            'Size',
            value => value && value.size <= FILE_SIZE
          )
          .test(
            'fileType',
            'Format',
            value => value && SUPPORTED_FORMATS.includes(value.type)
          )
    }
  }),How can I do it?
const imageWidthAndHeight = (provideFile) => {
    // take the given file (which should be an image) and return the width and height
    const imgDimensions = { width: null, height: null };
    return new Promise(resolve => {
        const reader = new FileReader();
        
        reader.readAsDataURL(provideFile);
        reader.onload = function () {
            const img = new Image();
            img.src = reader.result;
            img.onload = function () {
                imgDimensions.width = img.width;
                imgDimensions.height = img.height;
                resolve(imgDimensions);
            }
        };
    });
}
const imageDimensionCheck = Yup.addMethod(Yup.mixed, 'imageDimensionCheck', function (message, requiredWidth, requiredHeight) {
    return this.test("image-width-height-check", message, async function (value) {
        const { path, createError } = this;
        if (!value) {
            return;
        }
        const imgDimensions = await imageWidthAndHeight(value);
        if (imgDimensions.width !== requiredWidth) {
            return createError({
                path,
                message: `The file width needs to be the ${requiredWidth}px!`
              });
        }
        if (imgDimensions.height !== requiredHeight) {
            return createError({
                path,
                message: `The file height needs to be the ${requiredHeight}px!`
              });
        }
        return true;
    });
});
<Formik
    initialValues={{
        bookCoverPhoto: null,
    }}
    validationSchema={
        Yup.object().shape({
            bookCoverPhoto: Yup.mixed()
                .required('You need to provide a file')
                .imageDimensionCheck('test', 1988, 3056)
        })
    }
>
....Stuff
</Formik>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With