javascript Zod validator / validate image

jvidinwx  于 2023-11-15  发布在  Java
关注(0)|答案(4)|浏览(112)

我有一个问题,我需要验证一个图像与zod .我正在寻找3小时.我找不到验证图像?有人能帮我解决这个问题吗?zod必须有图像验证是?

const payloadSchema = z.object({
    image: z.record(z.string()),
})

字符串
找到这样的东西,但我怎么能添加的图像是3 MB的最大值,它的类型必须是“jpg““png“或“gif

4nkexdtk

4nkexdtk1#

试试这个,它看起来很简单,它对我很有效:

const MAX_FILE_SIZE = 5000000;
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对象还是File[]数组。我将它与react-dropzone一起使用,所以我将其配置为保存单个File对象。如果它是数组,则必须将模式更改为:

const MAX_FILE_SIZE = 5000000;
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."
    )
})

py49o6xq

py49o6xq2#

我遇到了和你一样的问题,并发现了一个更简单的方法来解决它。
我也在使用Dropzone,但如果你使用File类型,只要它不是矢量文件,概念是一样的。只是不要使用“transform”,并理解细化将是针对单个文件。

avatar: z
    .custom<FileList>()
    .transform((file) => file.length > 0 && file.item(0))
    .refine((file) => !file || (!!file && file.size <= 10 * 1024 * 1024), {
      message: "The profile picture must be a maximum of 10MB.",
    })
    .refine((file) => !file || (!!file && file.type?.startsWith("image")), {
      message: "Only images are allowed to be sent.",
    }),

字符串

qrjkbowd

qrjkbowd3#

我将通过为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类型。

wwwo4jvm

wwwo4jvm4#

试试这个。它为我工作。也请检查你是否有一个文件数组或文件对象,并作出相应的更改。我还添加了文件需要验证,如果需要的话

const MAX_FILE_SIZE = 3000000;
function checkFileType(file: File) { // file type checking
    if (file?.name) {
        const fileType = file.name.split(".").pop();
        if (["gif", "png", "jpg"].includes(fileType)) return true; 
    }
    return false;
}

export const fileSchema = z.object({
  z.any()
   .refine((file: File) => file?.length !== 0, "File is required") // If you also wanna validate if the file exists
   .refine((file) => file.size < MAX_FILE_SIZE, "Max size is 3MB.") // file size validation
   .refine((file) => checkFileType(file), "Only .jpg, .gif, .png formats are supported."),` 
});

字符串

相关问题