javascript - 使用 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)
)
}
}),
我该怎么做?
解决方案
- 创建一个将加载图像文件并返回尺寸的承诺
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 - 带数组的 JSON
- sql - 基于列组织表中的数据
- unity3d - Unity、Vr、Vive - 播放/暂停视频的控制器?
- lotus-notes - 注释 EMBEDDEDOBJECT (1090) 不返回内联图像
- c# - 如何在没有 Windows 窗体参考的情况下获得屏幕分辨率?
- java - 按分隔符数量拆分字符串
- sql - 将一列中的记录作为table1中的不同行从sql-server中table2的一行中的不同列插入
- python - 列表索引超出范围错误必须有索引指示
- sql - SQL 选择列 BLOB 数据的特定(第 4)部分,由特定模式分隔
- javascript - 使用php和mysql数据库的活动监控流程图