optional
Creates an optional schema.
const Schema = v.optional<TWrapped, TDefault>(wrapped, default_);
Generics
TWrappedextends BaseSchema<unknown, unknown, BaseIssue<unknown>>TDefaultextends Default<TWrapped, undefined>
Parameters
wrappedTWrappeddefault_TDefault
Explanation
With optional the validation of your schema will pass undefined inputs, and if you specify a default_ input value, the schema will use it if the input is undefined. For this reason, the output type may differ from the input type of the schema.
Important: When used in object schemas, if a key is missing and no
default_value is provided, the schema's pipe (including transformations) will not be executed. To ensure pipes run for missing keys, provide adefault_value.Note that
optionaldoes not acceptnullas an input. If you want to acceptnullinputs, usenullable, and if you want to acceptnullandundefinedinputs, usenullishinstead. Also, if you want to set a default output value for any invalid input, you should usefallbackinstead.
Returns
SchemaOptionalSchema<TWrapped, TDefault>
Examples
The following examples show how optional can be used.
Optional string schema
Schema that accepts string and undefined.
const OptionalStringSchema = v.optional(v.string(), "I'm the default!");
Optional date schema
Schema that accepts Date and undefined.
By using a function as the
default_parameter, the schema will return a newDateinstance each time the input isundefined.
const OptionalDateSchema = v.optional(v.date(), () => new Date());
Optional entry schema
Object schema with an optional entry.
const OptionalEntrySchema = v.object({
key: v.optional(v.string()),
});
Default to undefined
By default, when an object input is missing an optional entry, the corresponding key is omitted from the output. To always include the key in the output with an undefined value, pass a function that returns undefined as the default_ parameter.
const OptionalEntrySchema = v.object({
key: v.optional(v.string(), () => undefined),
});
Unwrap optional schema
Use unwrap to undo the effect of optional.
const OptionalNumberSchema = v.optional(v.number());
const NumberSchema = v.unwrap(OptionalNumberSchema);
Optional with pipes
When using optional in a pipe, the pipe actions only execute if a default_ value is provided or the key is present. This applies to all pipe actions including transform, check, and others.
const SchemaWithoutDefault = v.object({
isActive: v.pipe(
v.optional(v.string()),
v.transform((value) => value === 'true') // Does not run for missing keys
),
}); // Output type: { isActive?: boolean }
const SchemaWithDefault = v.object({
isActive: v.pipe(
v.optional(v.string(), 'false'), // Default value provided
v.transform((value) => value === 'true') // Runs for missing keys too
),
}); // Output type: { isActive: boolean }
Related
The following APIs can be combined with optional.
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, picklist, promise, record, 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, unwrap
Actions
check, brand, description, flavor, guard, metadata, partialCheck, rawCheck, rawTransform, readonly, title, transform
Utils
entriesFromList, isOfKind, isOfType
© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/optional/