Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating image's aspect ratio (width/height) with Yup & formik

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?

like image 437
wizzone Avatar asked Oct 25 '25 01:10

wizzone


1 Answers

  1. create a promise that will load the image file and return the dimension
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);
            }
        };
    });
}
  1. Call and await promise within a custom yup function (using addMethod) and add additional validation to check width and height.
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;
    });
});
  1. Call the created Yup method within formik
<Formik
    initialValues={{
        bookCoverPhoto: null,
    }}

    validationSchema={
        Yup.object().shape({
            bookCoverPhoto: Yup.mixed()
                .required('You need to provide a file')
                .imageDimensionCheck('test', 1988, 3056)
        })
    }
>
....Stuff
</Formik>
like image 139
Simone Anthony Avatar answered Oct 26 '25 15:10

Simone Anthony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!