guard

Creates a guard transformation action.

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

Generics

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

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.')
  ),
});

The following APIs can be combined with guard.

Schemas

Methods

Utils

Contributors

Thanks to all the contributors who helped make this page better!

  • GitHub profile picture of @EskiMojo14

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of @antfu
  • GitHub profile picture of @vasilii-kovalev
  • GitHub profile picture of @saturnonearth
  • GitHub profile picture of @ruiaraujo012
  • GitHub profile picture of @hyunbinseo
  • GitHub profile picture of @nickytonline
  • GitHub profile picture of @KubaJastrz
  • GitHub profile picture of @andrewmd5
  • GitHub profile picture of @Thanaen
  • GitHub profile picture of @caegdeveloper
  • GitHub profile picture of @bmoyroud
  • GitHub profile picture of @dslatkin