Skip to content

Add new requiredKeys option specifically for object keys #510

@nlf

Description

@nlf

The idea I had is to allow reusing a schema for CRUD purposes in an API easily. When creating an object many fields are required, however when updating that object those same fields may not be.

Currently you have to create two entirely separate schemas, one with the required fields and one without. For example:

var createSchema = Joi.object().keys({
  name: Joi.string().required(),
  age: Joi.number().integer().required
});

var updateSchema = Joi.object().keys({
  name: Joi.string(),
  age: Joi.number().integer()
});

What I'm envisioning is being able to extend an existing object schema by declaring an array of keys as required, so instead you could do:

var updateSchema = Joi.object().keys({
  name: Joi.string(),
  age: Joi.number().integer()
});

var createSchema = updateSchema.requiredKeys(['name', 'age']);

Alternatively you could so a similar thing with the optional method:

var createSchema = Joi.object().keys({
  name: Joi.string().required(),
  age: Joi.number().integer().required()
});

var updateSchema = createSchema.optionalKeys(['name', 'age']);

Thoughts?

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions