我有个问题,我需要用zod验证一个图像。我在搜索三个小时。我无法在验证图像时找到答案?有人能帮我解决这个问题吗?zod必须有图像验证是的?
const payloadSchema = z.object({
image: z.record(z.string()),
})找到这样的东西,但我如何添加的图像是3mbmax,它的类型必须是"jpg“"png”或"gif“
发布于 2022-06-26 05:42:10
为此,我将向File的zod模式添加一个细化。作为后续验证,可以使用superRefine助手将新问题附加到现有模式。
import { z } from 'zod';
const MB_BYTES = 1000000; // Number of bytes in a megabyte.
// This is the list of mime types you will accept with the schema
const ACCEPTED_MIME_TYPES = ["image/gif", "image/jpeg", "image/png"];
// This is a file validation with a few extra checks in the `superRefine`.
// The `refine` method could also be used, but `superRefine` offers better
// control over when the errors are added and can include specific information
// about the value being parsed.
const imageSchema = z.instanceof(File).superRefine((f, ctx) => {
// First, add an issue if the mime type is wrong.
if (!ACCEPTED_MIME_TYPES.includes(f.type)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `File must be one of [${ACCEPTED_MIME_TYPES.join(
", "
)}] but was ${f.type}`
});
}
// Next add an issue if the file size is too large.
if (f.size > 3 * MB_BYTES) {
ctx.addIssue({
code: z.ZodIssueCode.too_big,
type: "array",
message: `The file must not be larger than ${3 * MB_BYTES} bytes: ${
f.size
}`,
maximum: 3 * MB_BYTES,
inclusive: true
});
}
});这应该用您定义的参数进行验证,但前提是您有一个正在验证的File句柄。如果从<input type="file" />元素获取文件,则可能需要通过向输入添加accept属性来验证MIME类型。
发布于 2022-07-27 10:44:24
试试看,它看起来很简单,而且对我来说很管用:
const MAX_FILE_SIZE = 500000;
const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp"];
const someSchema = z.object({
image: z
.any()
.refine((file) => file?.size <= MAX_FILE_SIZE, `Max image size is 5MB.`)
.refine(
(file) => ACCEPTED_IMAGE_TYPES.includes(file?.type),
"Only .jpg, .jpeg, .png and .webp formats are supported."
)
})然后,应该用以下方式显示错误:
formState.errors?.image?.message但是要注意的一点是,您从输入中得到的是什么样的对象。检查它是文件对象还是File[]数组。我使用它与react下拉区域,所以我配置它来保存一个单一的File对象。如果它是一个数组,则必须将模式更改为:
const MAX_FILE_SIZE = 500000;
const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp"];
const someSchema = z.object({
image: z
.any()
.refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, `Max image size is 5MB.`)
.refine(
(files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type),
"Only .jpg, .jpeg, .png and .webp formats are supported."
)
})https://stackoverflow.com/questions/72674930
复制相似问题