variant

Creates a variant schema.

// Variant schema with an optional pipe
const Schema = variant<TKey, TOptions>(key, options, pipe);

// Variant schema with an optional message and pipe
const Schema = variant<TKey, TOptions>(key, options, message, pipe);

Generics

Parameters

Explanation

With variant you can validate if the input matches one of the given object options. The object schema to be used for the validation is determined by the discriminator key. With pipe you can transform and validate the further details of the variant. If the input does not match a schema and cannot be clearly assigned to one of the options, you can use message to customize the error message.

Returns

Examples

The following examples show how variant can be used.

Variant schema

Schema to validate an email, URL or date variant.

const VariantSchema = variant('type', [
  object({
    type: literal('email'),
    email: string([email()]),
  }),
  object({
    type: literal('url'),
    url: string([url()]),
  }),
  object({
    type: literal('date'),
    date: string([isoDate()]),
  }),
]);

Nested variant schema

You can also nest variant schemas.

const NestedVariantSchema = variant('type', [
  VariantSchema,
  object({
    type: literal('color'),
    date: string([hexColor()]),
  }),
]);

The following APIs can be combined with variant.

Schemas

Methods

Transformations

Validations

Contributors

Thanks to all the contributors who helped make this page better!

  • GitHub profile picture of fabian-hiller

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of dailydotdev
  • GitHub profile picture of ivan-mihalic
  • GitHub profile picture of KATT
  • GitHub profile picture of osdiab
  • GitHub profile picture of Thanaen
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of caegdeveloper