admin管理员组

文章数量:1418136

I am trying to do the validation using yup for image file, what I found was 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)
          )
    }
  }),

I am trying to do the validation using yup for image file, what I found was https://github./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?

Share Improve this question asked Nov 25, 2020 at 9:47 wizzonewizzone 1363 silver badges16 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3
  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>

I managed to do it by using this function

function checkAspectRatio(value) {
  return new Promise(resolve => {
    const reader = new FileReader();
    reader.readAsDataURL(value);
    reader.onload = function(value) {
      const img = new Image();
      img.src = value.target.result;
      img.onload = function() {
        const aspectRatio = this.width / this.height;
        resolve(aspectRatio);
      };
    };
  });
}

using Object.defineProperty() to define a new property on the object

Object.defineProperty(file, 'aspectRatio', {
  value: await checkAspectRatio(file)
});

and test the value using yup

.test(
  'fileAspectRatio',
  'Please recheck the image resolution',
  value => value && value.aspectRatio === 1.6
);

image: Yup.mixed()
  .required("Image is required.")
  .test(
    "aspectRatio",
    "Aspect ratio must be 16:9",
    value => {
      return new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(value[0]);
        reader.onload = function(value) {
          const img = new Image();
          img.src = value.target.result;
          img.onload = function() {
            const aspectRatio = this.width / this.height;
            resolve(aspectRatio === (16 / 9));
          };
        };
      });
    }
  ),

Here are two alternative method that are faster than (de)encoding to/from base64 and dose not need the filereader

function checkAspectRatio (file) {
    const img = new Image()
    img.src = URL.createObjectURL(file)
    return img.decode().then(() => {
        URL.revokeObjectURL(img.src)
        return img.width / img.height
    })
}

// not as cross patible
function checkAspectRatio (file) {
    return createImageBitmap(file)
      .then(bitmap => bitmap.width / bitmap.height)
}

本文标签: javascriptValidating image39s aspect ratio (widthheight) with Yup amp formikStack Overflow