You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zod如何为对象中两个数组的总长度设置不超过3的上限

实现方案

你可以使用Zod提供的refine方法在对象层面做跨字段校验,直接判断两个数组的长度总和即可,修改后的代码如下:

import { z } from "zod";

// 这里补充personalityEnum示例,你可以替换成自己的实际定义
const personalityEnum = z.enum(["内向", "外向", "乐观", "谨慎"]);

export const personality = z.object({
  enumInput: personalityEnum.array(),
  customInput: z.string().length(20).array()
// 追加对象级别的自定义校验规则
}).refine((data) => {
  // 计算两个数组的总长度,判断是否不超过3
  return data.enumInput.length + data.customInput.length <= 3;
}, {
  message: "enumInput和customInput的总条目数不能超过3",
  // 可自定义错误提示挂载的字段,不配置默认挂载在对象根层级
  path: ["enumInput"]
})

export type Personality = z.infer<typeof personality>

如果需要让两个字段同时触发错误提示,可以用更灵活的superRefine方法实现:

export const personality = z.object({
  enumInput: personalityEnum.array(),
  customInput: z.string().length(20).array()
}).superRefine((data, ctx) => {
  const total = data.enumInput.length + data.customInput.length;
  if (total > 3) {
    // 给enumInput添加错误
    ctx.addIssue({
      code: z.ZodIssueCode.too_big,
      maximum: 3,
      type: "array",
      inclusive: true,
      message: "总条目数不能超过3",
      path: ["enumInput"]
    });
    // 给customInput也添加错误
    ctx.addIssue({
      code: z.ZodIssueCode.too_big,
      maximum: 3,
      type: "array",
      inclusive: true,
      message: "总条目数不能超过3",
      path: ["customInput"]
    });
  }
})

内容的提问来源于stack exchange,提问作者branperr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:21:01