Skip to content

Support for union types in schemas. #197

@joshuafcole

Description

@joshuafcole

Hey folks, we really appreciate the work you've done with Joi. We use Hapi for our web server and are now looking to centralize all validation using a single set of Joi schemas for our mongo documents.

One of the few missing features that would be very useful is support for union types in schemas. This is useful in many cases -- all variants of providing an enumeration of valid types for a field. To give on example, it would be nice to implement a transparent reference function that can accept a value matching the schema or a value matching an identifying field in the schema, in the pattern:

function reference(schema, referenceField) {
  return Joi.any().validType(
    schema,
    schema[referenceField]
  );
}

var person = reference({
  id: Joi.number().integer(),
  name: Joi.string()
}, 'id');

var john = {
  id: 1,
  name: 'John Smith'
};

Joi.validate(john, person); // true
Joi.validate(1, person); // true

Which would return a type that would either accept a person value or a possible person id.

I'm hoping to graft Joi onto an ODM so we can use the same validation across the stack.

If there's anything I've missed that would let me already implement something similar please let me know. Otherwise, I'd be happy to do whatever I can to get some momentum behind this.

Cheers,
Josh

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