skip to Main Content

I’m using Joi for JSON schema validation, and I need to remove validation for a specific key (id) in a simple object within the main schema.

Here’s a example of my existing schema:

const schema = Joi.object({
  id: Joi.string().required(),
  operation: Joi.string().required(),
  // Other keys...
});

I attempted to create a new schema (newSchema) by using the .keys() method to remove the validation for the id key, similar to this:


const newSchema = schema.concat(Joi.object({
  id: Joi.any().optional(), // Attempted approach
}));

However, this approach doesn’t seem to work as intended.

I want to achieve a new schema that is the same as the original but without the validation for the id key:

How can I remove the validation for the id key in a simple object using Joi?

2

Answers


  1. Chosen as BEST ANSWER

    The overriding works when using .keys

    const newSchema = schema.keys({
      id: Joi.any().optional()
    });
    

  2. If you already know which types you are going through, you can use the alternatives (link to the doc here)

    So, if you would like to have string or integer numbers as id, you could do something like

    const schema = Joi.object({
     id: Joi.alternatives().try(Joi.number(), Joi.string()).required(),
     operation: Joi.string().required(),
      // Other keys...
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search