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

如何使用JOI验证器对嵌套JSON对象执行条件校验

问题原因

你现有代码的核心问题是when条件的字段引用范围错误:在LocationData子对象的校验规则中直接写userSelection,Joi默认会在当前LocationData对象下查找该字段,而不是向上查找父级parent对象下的userSelection,导致条件永远不触发,所以userSelection = No时的LocationData禁止规则失效。

修复后的完整校验规则
const Joi = require('joi');

const validateSchema = Joi.object({
  parent: Joi.object().required().keys({
    userSelection: Joi.string().valid("Yes", "No").required(),
    LocationData: Joi.object()
      .keys({
        name: Joi.string().min(3).max(100).required(),
        address: Joi.string().required(),
        latitude: Joi.number().min(-90).max(90).required(),
        longitude: Joi.number().min(-180).max(180).required()
      })
      // 此处when处于parent对象层级,可直接访问同级的userSelection字段
      .when("userSelection", {
        is: "Yes",
        then: Joi.required(),
        otherwise: Joi.forbidden()
      })
  })
});
规则说明
  • 当userSelection取值为Yes时:LocationData强制必填,且内部所有字段全部要求必填并符合格式约束,完全匹配你的需求
  • 当userSelection取值为No时:LocationData被标记为禁止字段,只要请求携带该字段就会直接返回校验错误,不会出现放行的问题
  • 废弃原来的requiredIfExist逻辑,因为LocationData只要出现就要求所有字段完整,不需要单独判断name是否存在

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:42:02