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

如何在Zod中获取min()、max()内设置的数值?

在Zod中获取字符串min()规则的数值方法

当然可以,Zod会把所有验证规则存储在schema的def.checks数组中,你可以通过这个结构提取min()设置的数值:

首先是你的原schema:

const schema = z.object({
  name: z.string().min(1)
})

然后通过以下代码获取min值:

// 取出name字段对应的string schema
const nameStringSchema = schema.shape.name;
// 在checks数组中筛选出类型为min的验证规则
const minRule = nameStringSchema.def.checks.find(rule => rule.kind === "min");
// 提取设置的数值
const minValue = minRule?.value; // 结果为1

补充说明

  • 每个Zod验证规则(比如min()、max()、email())都会以对象形式存在于def.checks数组中,其中kind字段标识规则类型,value字段存储你设置的具体参数。
  • 如果不确定该字段是否存在min()规则,建议用可选链?.或者提前判断,避免出现Cannot read properties of undefined的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:56:02