首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Zod验证器/验证映像

Zod验证器/验证映像
EN

Stack Overflow用户
提问于 2022-06-19 07:13:32
回答 2查看 839关注 0票数 4

我有个问题,我需要用zod验证一个图像。我在搜索三个小时。我无法在验证图像时找到答案?有人能帮我解决这个问题吗?zod必须有图像验证是的?

代码语言:javascript
复制
const payloadSchema = z.object({
    image: z.record(z.string()),
})

找到这样的东西,但我如何添加的图像是3mbmax,它的类型必须是"jpg“"png”或"gif

EN

回答 2

Stack Overflow用户

发布于 2022-06-26 05:42:10

为此,我将向File的zod模式添加一个细化。作为后续验证,可以使用superRefine助手将新问题附加到现有模式。

代码语言:javascript
复制
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类型。

票数 1
EN

Stack Overflow用户

发布于 2022-07-27 10:44:24

试试看,它看起来很简单,而且对我来说很管用:

代码语言:javascript
复制
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."
    )
})

然后,应该用以下方式显示错误:

代码语言:javascript
复制
formState.errors?.image?.message

但是要注意的一点是,您从输入中得到的是什么样的对象。检查它是文件对象还是File[]数组。我使用它与react下拉区域,所以我配置它来保存一个单一的File对象。如果它是一个数组,则必须将模式更改为:

代码语言:javascript
复制
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."
    )
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72674930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档