【问题标题】:Zod - Setting length limits to combined arrays in an objectZod - 为对象中的组合数组设置长度限制
【发布时间】:2021-09-01 19:38:02
【问题描述】:

我正在使用 Zod 来开发这些模式。我有一个包含两个字段的对象,每个字段都是一个数组。我想设置一个限制,使这两个数组的总长度不超过三个。关于如何解决这个问题的任何想法?代码如下。

export const personality = z.object({
   enumInput: personalityEnum.array(),
   customInput: z.string().length(20).array()
})

export type Personality = z.infer<typeof personality>

【问题讨论】:

    标签: typescript typescript-typings zod


    【解决方案1】:

    这里的答案有点晚,但我认为您可以使用refine 完成此操作:

    import { z } from "zod";
    enum PersonalityType {
      Grumpy = "grumpy",
      Sleepy = "sleepy",
      Bashful = "bashful"
    }
    const personalityEnum = z.enum([
      PersonalityType.Grumpy,
      PersonalityType.Sleepy,
      PersonalityType.Bashful
    ]);
    export const personality = z
      .object({
        enumInput: personalityEnum.array(),
        customInput: z.string().length(20).array()
      })
      .refine(
        (input) => {
          return input.customInput.length + input.enumInput.length <= 3;
        },
        {
          message:
            "The combined length of enumInput and customInput may not be longer than 3"
        }
      );
    
    export type Personality = z.infer<typeof personality>;
    
    const test1 = personality.safeParse({
      enumInput: [
        PersonalityType.Sleepy,
        PersonalityType.Grumpy,
        PersonalityType.Bashful
      ],
      customInput: ["Sneezy but length 20"]
    });
    // This fails with the custom error message
    const test2 = personality.safeParse({
      enumInput: [PersonalityType.Sleepy],
      customInput: ["Sneezy but length 20"]
    });
    // This succeeds!
    

    一边

    我在处理此问题时注意到.length(20) 改进意味着自定义输入必须恰好 20 个字符长。这是你想要的吗?如果您正在寻找最多 20 个字符的字符串,我认为 max(20) 就是您想要的。

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 2020-05-17
      • 1970-01-01
      • 2020-07-28
      • 2020-05-20
      • 2011-08-01
      • 2015-06-29
      • 2017-01-22
      相关资源
      最近更新 更多