record
Creates a record schema.
const Schema = v.record<TKey, TValue, TMessage>(key, value, message);
Generics
TKeyextends BaseSchema<string, string | number | symbol, BaseIssue<unknown>>TValueextends BaseSchema<unknown, unknown, BaseIssue<unknown>>TMessageextends ErrorMessage<RecordIssue> | undefined
Parameters
keyTKeyvalueTValuemessageTMessage
Explanation
With record you can validate the data type of the input and whether the entries matches key and value. If the input is not an object, you can use message to customize the error message.
This schema filters certain entries from the record for security reasons.
This schema marks an entry as optional if it detects that its key is a literal type. The reason for this is that it is not technically possible to detect missing literal keys without restricting the
keyschema tostring,enumandpicklist. However, ifenumandpicklistare used, it is better to useobjectwithentriesFromListbecause it already covers the needed functionality. This decision also reduces the bundle size ofrecord, because it only needs to check the entries of the input and not any missing keys.
Returns
SchemaRecordSchema<TKey, TValue, TMessage>
Examples
The following examples show how record can be used.
String record schema
Schema to validate a record with strings.
const StringRecordSchema = v.record(
v.string(),
v.string(),
'An object is required.'
);
Object record schema
Schema to validate a record of objects.
const ObjectRecordSchema = v.record(v.string(), v.object({ key: v.string() }));
Picklist as key
Schema to validate a record with specific optional keys.
const ProductRecordSchema = v.record(
v.picklist(['product_a', 'product_b', 'product_c']),
v.optional(v.number())
);
Enum as key
Schema to validate a record with specific optional keys.
enum Products {
PRODUCT_A = 'product_a',
PRODUCT_B = 'product_b',
PRODUCT_C = 'product_c',
}
const ProductRecordSchema = v.record(v.enum(Products), v.optional(v.number()));
Related
The following APIs can be combined with record.
Schemas
any, array, bigint, blob, boolean, custom, date, enum, exactOptional, file, function, instance, intersect, lazy, literal, looseObject, looseTuple, map, nan, never, nonNullable, nonNullish, nonOptional, null, nullable, nullish, number, object, objectWithRest, optional, picklist, promise, set, strictObject, strictTuple, string, symbol, tuple, tupleWithRest, undefined, undefinedable, union, unknown, variant, void
Methods
assert, config, fallback, getDefault, getDefaults, getFallback, getFallbacks, is, message, parse, parser, pipe, safeParse, safeParser
Actions
check, brand, description, entries, flavor, guard, maxEntries, minEntries, metadata, partialCheck, rawCheck, rawTransform, readonly, title, transform
Utils
entriesFromList, isOfKind, isOfType
© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/record/