JOI alternatives try - need one to be required

Viewed 8077

I'm trying to validate a query string using JOI and express-validation.

I need the query param ?query[primaryOrgId]=5d2f2c836aeed10026ccba11 to be either a single string or an array of strings, and it is required.

The following schema is validating the primaryOrgId as expected when it is present, but it is not validating that it is required:

 index: {
    body: {},
    query: {
      query: {
        primaryOrgId: Joi.alternatives().try(
          Joi.array().items(Joi.string().regex(mongoId)),
          Joi.string().regex(mongoId),
        ).required()
      },
    },
    options: {
      allowUnknownQuery: false,
      allowUnknownBody: false,
    },
  },

I've also tried:

 index: {
    body: {},
    query: {
      query: {
        primaryOrgId: Joi.alternatives().try(
          Joi.array().items(Joi.string().regex(mongoId).required()),
          Joi.string().regex(mongoId).required(),
        )
      },
    },
    options: {
      allowUnknownQuery: false,
      allowUnknownBody: false,
    },
  },
}

How can I ensure that primaryOrgId is present in the query string?

1 Answers

I am not 100% sure about your requirements, but here is a Joi ("@hapi/joi": "^17.1.1") schema with a few changes:

const schema = Joi.alternatives().try(
  Joi.array().min(1).items(Joi.string().trim()), // length have to be at least 1
  Joi.string().trim()
).required(); // required added

// String
console.log(schema.validate(undefined)); // error: [Error [ValidationError]: "value" is required]
console.log(schema.validate('')); // error: [Error [ValidationError]: "value" is not allowed to be empty]
console.log(schema.validate(' ')); // error: [Error [ValidationError]: "value" is not allowed to be empty]
console.log(schema.validate('foo')); // value: 'foo'

// Array
console.log(schema.validate([])); // error: [Error [ValidationError]: "value" must contain at least 1 items]
console.log(schema.validate([' '])); // error: [Error [ValidationError]: "[0]" is not allowed to be empty]
console.log(schema.validate(['foo'])); // value: [ 'foo' ]
console.log(schema.validate(['foo', 'bar'])); //  value: [ 'foo', 'bar' ]

Let me know if this works well for you. Otherwise I will update my answer.

Related