Spec-Zone.ru › Valibot

guard

Creates a guard transformation action.

const Action = v.guard<TInput, TGuard, TMessage>(requirement, message);

Generics

  • TInput extends any
  • TGuard extends GuardFunction<TInput>
  • TMessage extends ErrorMessage<GuardIssue<TInput, TGuard>> | undefined

Parameters

  • requirement TGuard
  • message TMessage

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).

guard is useful for narrowing known types. For validating completely unknown values, consider custom instead.

Returns

  • Action GuardAction<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

forward, pipe

Utils

isOfKind, isOfType

© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/guard/

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API