required
Creates a modified copy of an object schema that marks all or only the selected entries as required.
const AllKeysSchema = v.required<TSchema, TMessage>(schema, message);
const SelectedKeysSchema = v.required<TSchema, TKeys, TMessage>(
schema,
keys,
message
);
Generics
TSchemaextends SchemaWithoutPipe<LooseObjectSchema<ObjectEntries, ErrorMessage<LooseObjectIssue> | undefined> | ObjectSchema<ObjectEntries, ErrorMessage<ObjectIssue> | undefined> | ObjectWithRestSchema<ObjectEntries, BaseSchema<unknown, unknown, BaseIssue<unknown>>, ErrorMessage<ObjectWithRestIssue> | undefined> | StrictObjectSchema<ObjectEntries, ErrorMessage<StrictObjectIssue> | undefined>>TKeysextends ObjectKeys<TSchema>TMessageextends ErrorMessage<NonOptionalIssue> | undefined
Parameters
schemaTSchemakeysTKeymessageTMessage
Explanation
required creates a modified copy of the given object schema where all or only the selected keys are required. It is similar to TypeScript's Required utility type.
Because
requiredchanges the data type of the input and output, it is not allowed to pass a schema that has been modified by thepipemethod, as this may cause runtime errors. Please use thepipemethod after you have modified the schema withrequired.
Returns
AllKeysSchemaSchemaWithRequired<TSchema, undefined, TMessage>SelectedKeysSchemaSchemaWithRequired<TSchema, Tkeys, TMessage>
Examples
The following examples show how required can be used.
Required object schema
Schema to validate an object with required entries.
const RequiredSchema = v.required(
v.object({
key1: v.optional(v.string()),
key2: v.optional(v.number()),
})
); // { key1: string; key2: number }
With only specific keys
Schema to validate an object with only specific entries marked as required.
const RequiredSchema = v.required(
v.object({
key1: v.optional(v.string()),
key2: v.optional(v.number()),
key3: v.optional(v.boolean()),
}),
['key1', 'key3']
); // { key1: string; key2?: number; key3: boolean }
Related
The following APIs can be combined with required.
Schemas
array, exactOptional, intersect, lazy, looseObject, looseTuple, map, nonNullable, nonNullish, nonOptional, nullable, nullish, object, objectWithRest, optional, record, set, strictObject, strictTuple, tuple, tupleWithRest, undefinedable, union
Methods
assert, config, fallback, forward, getDefault, getDefaults, getFallback, getFallbacks, is, keyof, message, omit, parse, parser, partial, pick, safeParse, safeParser, unwrap
Actions
brand, check, description, entries, flavor, guard, maxEntries, metadata, minEntries, notEntries, partialCheck, rawCheck, rawTransform, readonly, title, transform
Utils
© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/required/