首页 > 解决方案 > 使用 Yup & formik 验证图像的纵横比(宽度/高度)

问题描述

我正在尝试使用 yup 对图像文件进行验证,我发现https://github.com/formium/formik/issues/926仅验证大小和文件类型。

这是我使用的当前 yup 验证

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

我该怎么做?

标签: javascriptformikyup

解决方案


  1. 创建一个将加载图像文件并返回尺寸的承诺
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. 在自定义 yup 函数(使用 addMethod)中调用和等待 promise,并添加额外的验证来检查宽度和高度。
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. 在 formik 中调用创建的 Yup 方法
<Formik
    initialValues={{
        bookCoverPhoto: null,
    }}

    validationSchema={
        Yup.object().shape({
            bookCoverPhoto: Yup.mixed()
                .required('You need to provide a file')
                .imageDimensionCheck('test', 1988, 3056)
        })
    }
>
....Stuff
</Formik>

推荐阅读