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

Node项目Joi验证实现:仅允许a&b或c&d字段组合

实现Joi数据校验:仅允许{a,b}或{c,d}两种对象结构

嘿,这个需求我之前做Node.js项目时刚好碰到过类似的,用Joi的**alternatives(分支校验)**结合对象键的约束就能完美解决,完全符合你要的“仅允许两组键对中的一组”的规则。

核心实现代码

const Joi = require('joi');

// 定义校验规则
const targetSchema = Joi.alternatives().try(
  // 规则1:仅包含a和b,且两者都必填
  Joi.object({
    a: Joi.any().required(), // 这里可以替换成具体类型,比如Joi.string().required()
    b: Joi.any().required()
  }).unknown(false).length(2),
  // 规则2:仅包含c和d,且两者都必填
  Joi.object({
    c: Joi.any().required(),
    d: Joi.any().required()
  }).unknown(false).length(2)
);

关键规则解释

  • Joi.alternatives().try(...):用来定义两种互斥的有效结构,只要对象满足其中一种规则,校验就通过
  • .unknown(false):严格禁止对象包含规则中未定义的键,直接拦截像{a,b,c}这种混合键的情况
  • .length(2):强制对象的键数量必须为2,这样就排除了仅单个键(比如{a})、空对象{}这类无效情况
  • Joi.any().required():确保指定的键必须存在且有值,你可以根据实际需求换成具体类型校验(比如Joi.number().required()、Joi.string().max(100).required())

测试验证

你可以用下面的代码测试各种场景:

// 有效案例
console.log(targetSchema.validate({ a: 'test', b: 123 }).error); // null(校验通过)
console.log(targetSchema.validate({ c: true, d: [] }).error); // null(校验通过)

// 无效案例
console.log(targetSchema.validate({ a: 'test', b: 123, c: 'extra' }).error); // 存在错误(含额外键)
console.log(targetSchema.validate({ a: 'test' }).error); // 存在错误(键数量不足)
console.log(targetSchema.validate({}).error); // 存在错误(空对象)
console.log(targetSchema.validate({ a: 'test', c: 'mix' }).error); // 存在错误(混合不同组的键)

这样就能精准满足你的校验需求啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 15:13:14