Enums

An enumerated type is a data type that consists of a set of values. They can be represented by either an object, a TypeScript enum or, to keep things simple, an array. You use enum for objects and TypeScript enums and picklist for arrays.

Enum schema

Since TypeScript enums are transpiled to JavaScript objects by the TypeScript compiler, you can use the enum schema function for both. Just pass your enumerated data type as the first argument to the schema function. On validation, the schema checks whether the input matches one of the values in the enum.

import * as v from 'valibot';

// As JavaScript object
const Direction = {
  Left: 'LEFT',
  Right: 'RIGHT',
} as const;

// As TypeScript enum
enum Direction {
  Left = 'LEFT',
  Right = 'RIGHT',
}

const DirectionSchema = v.enum(Direction);

Picklist schema

For a set of values represented by an array, you can use the picklist schema function. Just pass your array as the first argument to the schema function. On validation, the schema checks whether the input matches one of the items in the array.

import * as v from 'valibot';

const Direction = ['LEFT', 'RIGHT'] as const;

const DirectionSchema = v.picklist(Direction);

Format array

In some cases, the array may not be in the correct format. In this case, simply use the .map() method to bring it into the required format.

import * as v from 'valibot';

const countries = [
  { name: 'Germany', code: 'DE' },
  { name: 'France', code: 'FR' },
  { name: 'United States', code: 'US' },
] as const;

const CountrySchema = v.picklist(countries.map((country) => country.code));

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 antfu
  • GitHub profile picture of Thanaen
  • GitHub profile picture of osdiab
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of F0rce
  • GitHub profile picture of Unique-Pixels
  • GitHub profile picture of jdgamble555
  • GitHub profile picture of nickytonline
  • GitHub profile picture of KubaJastrz
  • GitHub profile picture of caegdeveloper
  • GitHub profile picture of dslatkin