joi验证:必填字段取决于ohers字段

问题描述

我在节点项目中使用joi验证。我有以下需求:

我收到带有以下键的对象:

  • a
  • b
  • c
  • d

并非所有键都需要一起使用,但只有有效的对象是:

  • 仅定义了a和b键
  • 仅定义了c和d键

其他所有情况均应无效

有效对象示例:

{
  a:'',b:''
}

{
  c:'',d:''
}

示例无效对象:

{
  a:'',b:'',c:'',}

{
  a:''
}

{
}

...

预先感谢

解决方法

Joi版本 17.2.1

我知道如何执行此操作的两个选择:

选项1

const joi = require('joi');

const schema = joi.object().keys({
  a: joi.string(),b: joi.string(),c: joi.string(),d: joi.string(),})
.xor('a','c')
.xor('a','d')
.xor('b','c')
.xor('b','d')
.required();

选项2

const joi = require('joi');

const schema = joi.alternatives().try(
  joi.object({
    a: joi.string().required(),b: joi.string().required()
  }),joi.object({
    c: joi.string().required(),d: joi.string().required(),})
);

运行一些测试:

// should work
const aAndB = {
  a: 'a',b: 'b'
};
console.log(schema.validate(aAndB).error);

// should work
const cAndD = {
  c: 'c',d: 'd'
};
console.log(schema.validate(cAndD).error);


// should not work
const aAndC = {
  a: 'a',c: 'c'
};
console.log(schema.validate(aAndC).error);


// should not work
const onlyA = {
  a: 'a',};
console.log(schema.validate(onlyA).error);

// should not work
const onlyB = {
  b: 'b',};
console.log(schema.validate(onlyB).error);

// should not work
const onlyC = {
  c: 'c',};
console.log(schema.validate(onlyC).error);

// should not work
const onlyD = {
  d: 'd',};
console.log(schema.validate(onlyD).error);