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

如何使用Joi根据另一个属性的值生成新属性?

解决Joi中派生字段passportSeries的定义问题

你可以通过when结合default的方式实现需求,不管输入里有没有passportSeries字段,都会根据passport的存在情况自动生成对应值:

const schema = customJoi.object({
  passport: customJoi.string().optional().strip(true),
  passportSeries: customJoi.string().optional()
    .when('passport', {
      is: customJoi.exist(), // 匹配passport存在的场景
      then: customJoi.default((parent) => parent.passport.slice(0, 4)), // 截取前4位
      otherwise: customJoi.default(undefined) // 不存在则设为undefined
    })
});

如果希望完全忽略输入中的passportSeries,强制由passport生成值,可以给passportSeries加上strip(true),确保输入里的该字段被移除,只用派生值:

passportSeries: customJoi.string().optional().strip(true)
  .when('passport', {
    is: customJoi.exist(),
    then: customJoi.default((parent) => parent.passport.slice(0, 4)),
    otherwise: customJoi.default(undefined)
  })

另外提一句,单独用custom方法的话,只有当passportSeries在输入中存在时才会触发函数逻辑,没法处理输入里没有这个字段的场景,所以更推荐上面的when+default方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:30:26