简体   繁体   中英

How to do validation in Joi for alternative values?

I wanted to do validation of request body using joi validator. I will explain the exact use case by this snippet:-

const bodySchema=Joi.object().keys({
   userRef: Joi.string().length(24),
   userDetails: Joi.object()
    .keys(userDetailObj)
    .when('userRef', {
      is: Joi.exist(),
      then: {},
      otherwise: Joi.object().keys({
         firstName:Joi.string().required(),
         lastName:Joi.string().required()
      }).required(),
     }),
    });

In this snippet I want an empty object if userRef exists, same goes for userDetails if userDetails exists then I don't want userRef field but it is not working. Please help me to solve out this problem. Thanks in advance.

joi version 17.2.1

Either:

{
  "title": "title",
  "description": "description",

  "userRef": "aaaaaaaaaaaaaaaaaaaaaaaa"
}

Or:

{
  "title": "title",
  "description": "description",

  "userDetails": {
    "firstName": "first",
    "lastName": "last"
  }
}

Solution with tests:

const schema = Joi.alternatives().try(
  Joi.object().keys({
    title:Joi.string().required(),
    description:Joi.string().required(),
  
    userRef: Joi.string().length(24).required(),
  }).required(),
  Joi.object().keys({
    title:Joi.string().required(),
    description:Joi.string().required(),
  
    userDetails: Joi.object().keys({
      firstName: Joi.string().required(),
      lastName: Joi.string().required()  
    }).required(),
  }),
);



// works
const data1 = {
  title: 'title',
  description: 'description',

  userRef: 'aaaaaaaaaaaaaaaaaaaaaaaa',
};
console.log(schema.validate(data1).error);

// fails
const data2 = {
};
console.log(schema.validate(data2).error.message);

// works
const data3 = {
  title: 'title',
  description: 'description',

  userDetails: {
    firstName: 'first',
    lastName: 'last',
  },
};
console.log(schema.validate(data3).error);

// fails
const data4 = {
  title: 'title',
  description: 'description',

  userRef: 'a'.repeat(24),
  userDetails: {
    firstName: 'first',
    lastName: 'last',
  },
};
console.log(schema.validate(data4).error.message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM