如何使用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
相关产品推荐
相关产品推荐

