guard
Creates a guard transformation action.
const Action = v.guard<TInput, TGuard, TMessage>(requirement, message);
Generics
TInputextends anyTGuardextends GuardFunction<TInput>TMessageextends ErrorMessage<GuardIssue<TInput, TGuard>> | undefined
Parameters
requirementTGuardmessageTMessage
Explanation
With guard you can freely validate the input and return true if it is valid or false otherwise. If the input does not match your requirement, you can use message to customize the error message.
This is especially useful if you have an existing type predicate (for example, from an external library).
guardis useful for narrowing known types. For validating completely unknown values, considercustominstead.
Returns
ActionGuardAction<TInput, TGuard, TMessage>
Examples
The following examples show how guard can be used.
Pixel string schema
Schema to validate a pixel string.
const PixelStringSchema = v.pipe(
v.string(),
v.guard((input): input is `${number}px` => /^\d+px$/.test(input))
);
Axios Error schema
Schema to validate an object containing an Axios error.
import { isAxiosError } from 'axios';
const AxiosErrorSchema = v.object({
error: v.pipe(
v.instance(Error),
v.guard(isAxiosError, 'The error is not an Axios error.')
),
});
Related
The following APIs can be combined with guard.
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, record, set, strictObject, strictTuple, string, symbol, tuple, tupleWithRest, undefined, undefinedable, union, unknown, variant, void
Methods
Utils
© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/guard/