Zod 处理图像对象

问题描述 投票:0回答:1

我正在使用

react-file-base64
,它提供文件的元数据,例如名称、文件类型、大小、base64 编码,我注册了 zod 验证,即使我上传了图像,zod 也会抛出“图像需要错误”。我交叉验证,zod不接受任何图像对象来验证,如何处理这个错误。

interface featured_image_types {
    name: string;
    type: string;
    size: string;
    base64: string
}

 const schema = z.object({
        blog: z.any({ required_error: "Please enter a blog content, it cannot be empty!!!" }),
        title: z.string().min(5, { message: "Title should be atleast minimum 5 characters" }).refine((val) => console.log(val)),
        reading_time: z.string({ required_error: "Reading Time required" }),
        featured_image:  z
        .any()
        // Custom refinement function to log files
        .refine((files) => {
        console.log(files, "this not rertriviing files here");
          // Return null to ensure the validation continues
        return true;
        })
        // To not allow empty files
        .refine((files) => files?.length >= 1, { message: 'Image is required.' })
        // To not allow files other than images
        .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
        message: '.jpg, .jpeg, .png and .webp files are accepted.',
        })
        // To not allow files larger than 5MB
        .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
        message: `Max file size is 5MB.`,
        }),
        blog_cat: z.string({ required_error: "Please select one of blog cateogry" }).min(6, { message: "Please select one of blog cateogry" }),
        tags: z.any()
    })
    
<div>
<label className="block mb-2 text-sm font-bold" htmlFor="file_input">Featured Image</label>

 <FileBase
     type = 'file'
     {...register('featured_image')}
     multiple={false}
     onDone={(file: featured_image_types) => setSomething({ ...something, featured_image: file })}
                            />

    {errors.featured_image && <p className="text-red-500">{errors?.featured_image?.message?.toString()}</p>}

                        </div>
                        
                        
// This part return undefined
.refine((files) => {
        console.log(files, "this not rertriviing files here");
          // Return true to ensure the validation continues
        })

javascript typescript zod
1个回答
0
投票

两个建议:

  • 采用您的架构,并在 REPL、浏览器控制台或类似设备中进行试验。尝试解析不同的输入并查看其行为。

例如:

z.any().refine(it => {console.log(it); return true}).parse('anything')
  • 考虑使用
    z.array(z.object{name: z.string(), ... })
    而不是依赖这么多
    refine
    。您可能仍然需要一些改进,但我认为您最终会得到更具可读性/更清晰的结果

我不认为你的

zod
模式是这个例子中的问题 - 我会记录你传递给
schema.parse
的值并检查它。我怀疑
featured_image
属性丢失了。

© www.soinside.com 2019 - 2024. All rights reserved.