gpt4 book ai didi

javascript - 使用 Yup & formik 验证图像的纵横比(宽度/高度)

转载 作者:行者123 更新时间:2023-12-05 00:38:25 24 4
gpt4 key购买 nike

我正在尝试使用 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)
)
}
}),

我该怎么做?

最佳答案

  • 创建一个将加载图像文件并返回维度
  • 的 promise
    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);
    }
    };
    });
    }
  • 在自定义 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;
    });
    });
  • 在 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>

    关于javascript - 使用 Yup & formik 验证图像的纵横比(宽度/高度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65002123/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com