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

如何在express-validator中根据请求体动态选择checkSchema?

基于请求体字段的动态Schema校验方案(使用checkSchema)

要实现根据请求体中Type字段的值动态启用校验规则的需求,无需拆分多个独立Schema,直接在checkSchema中通过条件校验逻辑即可完成。以下是两种实用方案:

方案1:使用自定义校验函数(custom)

适合处理复杂的条件校验逻辑,直接在字段规则中编写判断逻辑:

const { checkSchema, validationResult } = require('express-validator');

const dynamicSchema = {
  Type: {
    in: 'body',
    notEmpty: {
      errorMessage: "'Type' 必须在请求体中提供"
    }
  },
  SomeData: {
    in: 'body',
    custom: {
      options: (value, { req }) => {
        // 仅当Type为"A"时才校验SomeData
        if (req.body.Type === 'A') {
          if (!value) {
            throw new Error("'SomeData' 必须在请求体中提供");
          }
          try {
            JSON.parse(value);
          } catch (err) {
            throw new Error("'SomeData' 必须是合法的JSON格式");
          }
        }
        // Type不为"A"时直接通过校验
        return true;
      }
    }
  }
};

// 路由中使用示例
app.post('/api/your-endpoint', checkSchema(dynamicSchema), (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // 执行业务逻辑
  res.status(200).json({ success: true });
});

方案2:使用if/then条件规则

更贴合checkSchema的声明式语法,适合简单的条件触发场景:

const { checkSchema, validationResult } = require('express-validator');

const dynamicSchema = {
  Type: {
    in: 'body',
    notEmpty: {
      errorMessage: "'Type' 必须在请求体中提供"
    }
  },
  SomeData: {
    in: 'body',
    // 定义触发条件:Type等于"A"时启用后续规则
    if: {
      options: (_, { req }) => req.body.Type === 'A'
    },
    // 条件满足时应用的校验规则
    then: {
      notEmpty: {
        errorMessage: "'SomeData' 必须在请求体中提供"
      },
      isJSON: {
        errorMessage: "'SomeData' 必须是合法的JSON格式"
      }
    }
  }
};

方案说明

  • 两种方案均无需拆分Schema,直接在同一个Schema中完成动态校验逻辑
  • 自定义函数(custom)灵活性更高,可处理多分支、嵌套等复杂校验场景
  • if/then规则更简洁直观,适合单一条件触发的校验需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 12:27:34