record
An object with arbitrary keys — a dictionary. All values are validated with one schema, and optionally the keys too.
Signature
ts
function record<V>(value: Schema<V>, msg?: Message): Schema<Record<string, V>>
function record<K extends string, V>(key: Schema<K>, value: Schema<V>, msg?: Message): Schema<Record<K, V>>Parameters
| Parameter | Type | Description |
|---|---|---|
key | Schema<K> | Optional key schema: pipe(string(), pattern(...)), oneOf([...]) |
value | Schema<V> | Value schema |
msg | Message | Custom message if the value is empty or not an object |
Notes
- Key and value errors are attached to that key's path:
errors.ab. - If the key schema transforms the key (e.g.
toLowerCase),datagets the transformed key. - Only own keys are read. A
__proto__key from JSON is safe — it doesn't change the result's prototype.
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty | Required |
object | Not an object (or an array) | Must be an object |
Examples
Translations
ts
const title = record(oneOf(['ru', 'en', 'zh']), pipe(string(), maxLength(200)));
// Record<'ru' | 'en' | 'zh', string>
validate(title, { ru: 'Привет', en: 'Hello' }).valid; // true
validate(title, { de: 'Hallo' }).errors; // { de: 'Must be one of: ru, en, zh' }Quantities by product ID
ts
const cart = record(pipe(string(), pattern(/^\d+$/)), pipe(number(), integer(), min(1)));
validate(cart, { '15': 2, '42': 1 }).data; // { '15': 2, '42': 1 }