简体   繁体   中英

How to validade if an Array contains another key value using Joi?

I wanna validate that the driverId cannot be in the passengersId, so I tried this:

    driverId: Joi
        .string()
        .min(24)
        .max(24)
        .alphanum()
        .required(),

    passengersId: Joi
        .array()
        .items(Joi.string().min(24).max(24).alphanum(), Joi.string().label('driverId').forbidden())
        .min(1)
        .required(),

But it won't allow any id inside the passengers Id that match the driverId format.

Request:

{
    "date": "2020-05-06",
    "driverId": "5eef835636187301529b312c",
    "passengersId": ["5eef835636187301529b312c","5eef847088632e0178c2e85b"],
    "destinyId": "5eed7c3b5149460a45b85091"
}

Validation:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "\"passengersId[0]\" contains an excluded value. \"passengersId[1]\" contains an excluded value",
  "validation": {
    "source": "body",
    "keys": [
      "passengersId.0",
      "passengersId.1"
    ]
  }
}

EDIT1: If I validate like this, it works, but when trying to use Joi.ref('driverId') inside valid() , it doesn't work.

passengersId: Joi
        .array()
        .items(Joi.string().min(24).max(24).alphanum(), Joi.string().valid('5eef835636187301529b312c').forbidden())
        .required(),

SOLVED: Using Joi.in and '/' before the key's name to reference a previous key.

source that I use to solve the problem: LINK

passengersId: Joi
            .array()
            .items(Joi.string().min(24).max(24).alphanum(), Joi.string().valid(Joi.in('/driverId')).forbidden())
            .required(),

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