joi validation : field required depending of ohers fields

1k Views Asked by At

I am using joi validation in a node project. I have the following need :

I receive an object with the following keys :

  • a
  • b
  • c
  • d

All the keys are not required together, but only valid object is if :

  • only a and b keys are defined
  • only c and d keys are defined

every other case should be invalid

Exemple of valid objects :

{
  a:'',
  b:''
}

{
  c:'',
  d:''
}

Exemple of invalid objects :

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

{
  a:''
}

{
}

...

Thanks in advance

1

There are 1 best solutions below

1
On

Joi version 17.2.1

I know of two options on how to do this:

Option 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();

Option 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(),
  })
);

Run some tests:

// 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);