variant

Creates a variant schema.

const Schema = v.variant<TKey, TOptions, TMessage>(key, options, message);

Generics

Parameters

  • key TKey
  • options TOptions
  • message TMessage

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. 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.

It is allowed to specify the exact same or a similar discriminator multiple times. However, in such cases variant will only return the output of the first untyped or typed variant option result. Typed results take precedence over untyped ones.

Returns

Examples

The following examples show how variant can be used.

Variant schema

Schema to validate an email, URL or date variant.

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

Nested variant schema

You can also nest variant schemas.

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

The following APIs can be combined with variant.

Schemas

Methods

Actions

Utils

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 Thanaen
  • GitHub profile picture of KATT
  • GitHub profile picture of osdiab
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of F0rce
  • GitHub profile picture of caegdeveloper
  • GitHub profile picture of luckasnix