nullable
Creates a nullable schema.
const Schema = v.nullable<TWrapped, TDefault>(wrapped, default_);
Generics
TWrappedextends BaseSchema<unknown, unknown, BaseIssue<unknown>>TDefaultextends Default<TWrapped, null>
Parameters
wrappedTWrappeddefault_TDefault
Explanation
With nullable the validation of your schema will pass null inputs, and if you specify a default_ input value, the schema will use it if the input is null. For this reason, the output type may differ from the input type of the schema.
Note that
nullabledoes not acceptundefinedas an input. If you want to acceptundefinedinputs, useoptional, 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
SchemaNullableSchema<TWrapped, TDefault>
Examples
The following examples show how nullable can be used.
Nullable string schema
Schema that accepts string and null.
const NullableStringSchema = v.nullable(v.string(), "I'm the default!");
Nullable date schema
Schema that accepts Date and null.
By using a function as the
default_parameter, the schema will return a newDateinstance each time the input isnull.
const NullableDateSchema = v.nullable(v.date(), () => new Date());
Nullable entry schema
Object schema with a nullable entry.
const NullableEntrySchema = v.object({
key: v.nullable(v.string()),
});
Unwrap nullable schema
Use unwrap to undo the effect of nullable.
const NullableNumberSchema = v.nullable(v.number());
const NumberSchema = v.unwrap(NullableNumberSchema);
Related
The following APIs can be combined with nullable.
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, nullish, number, object, objectWithRest, optional, 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/nullable/