⚠️ This project is still in early alpha. Please report bugs on GitHub.

Schemas
Enum

Enum schema

A function which creates a parsing rule to ensure that a given value is one of the allowed values from an array or TypeScript enum.

Arguments

  1. values - An array of values or TypeScript enum
  2. message? - A custom object with error messages to be displayed when validation fails or there are type errors

Examples

import { enum_ } from '@nordic-ui/validathor';
 
const colorRule = enum_(['red', 'green', 'blue'] as const);
 
try {
  const parsedValue = colorRule.parse('red');
  console.log('Parsed value:', parsedValue);
} catch (error) {
  console.error('Parsing failed:', error.message);
}

TypeScript

To get the type of a schema, you can do the following:

As you can see here, using readonly arrays give better type safety.

const colorRule = enum_(['red', 'green', 'blue']);
const permissionRule = enum_(['read', 'write', 'admin'] as const);
 
type ColorSchema = ReturnType<typeof colorRule.parse>; // string
type PermissionSchema = ReturnType<typeof permissionRule.parse>; // 'read' | 'write' | 'admin'