### Valibot Development Setup and Usage Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/blog/(posts)/first-draft-of-the-new-pipe-function/index.mdx Provides bash commands for cloning the Valibot repository, switching to the rewrite branch, installing dependencies, building the library, and running a playground for testing. This is useful for developers wanting to contribute or test the latest changes. ```bash # Clone repository git clone git@github.com:open-circle/valibot.git # Switch branch git switch rewrite-with-pipe # Install dependencies cd ./valibot && pnpm install # Bundle library cd ./library && pnpm build # Modify `playground.ts` # Run playground pnpm play ``` -------------------------------- ### AI Metadata with Examples Action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/blog/(posts)/valibot-v1.2-release-notes/index.mdx Learn how to use the `examples()` action in Valibot to attach example values to schemas, facilitating integration with AI tools and automatic documentation generation. ```APIDOC ## Examples for AI tools and documentation ### Description The `examples()` action allows you to attach example values to any schema in Valibot. This metadata is crucial for integrating with AI-powered applications, generating documentation, and creating test fixtures. When multiple `examples()` actions are present, `getExamples()` concatenates them. ### Method N/A (Valibot is a library, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```ts import * as v from 'valibot'; const UserSchema = v.object({ id: v.pipe( v.string(), v.uuid(), v.examples(['550e8400-e29b-41d4-a716-446655440000']) ), name: v.pipe( v.string(), v.nonEmpty(), v.examples(['Alice Smith', 'Bob Johnson']) ), email: v.pipe( v.string(), v.email(), v.examples(['alice@example.com', 'bob@example.com']) ), }); // Extract email examples const emailExamples = v.getExamples(UserSchema.entries.email); ``` ### Response N/A ``` -------------------------------- ### Retrieve Schema Examples with getExamples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(methods)/getExamples/index.mdx Demonstrates the basic usage of the getExamples function to extract examples from a Valibot schema. It takes a schema as input and returns an array of defined example values. ```typescript const examples = v.getExamples(schema); ``` -------------------------------- ### Start Development Website Source: https://github.com/open-circle/valibot/blob/main/website/README.md Navigates to the website directory and starts the local development server. ```bash cd ../website && pnpm start ``` -------------------------------- ### Create Examples Action - TypeScript Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/examples/index.mdx Defines the `examples` action for Valibot, which allows specifying example values for a given schema. This is useful for generating documentation or providing context to AI models. It accepts generic types for input and examples. ```typescript import { ApiList, Property } from '~/components'; import { properties } from './properties'; const Action = v.examples(examples_); ``` -------------------------------- ### Valibot Examples Action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/examples/index.mdx Creates an examples metadata action for Valibot schemas. ```APIDOC ## Valibot Examples Action ### Description Creates an examples metadata action for Valibot schemas. This action allows you to associate example values with a schema, which can be beneficial for documentation generation or integration with AI tools. ### Method N/A (This is a conceptual API documentation for a library function, not a REST endpoint) ### Endpoint N/A ### Parameters #### Generics - **TInput** (Property): Represents the input type for the schema. - **TExamples** (Property): Represents the type of the examples provided. #### Function Parameters - **examples_** (Property): The function or value that provides the examples. ### Returns - **Action** (Property): The created metadata action. ### Examples #### String Schema Example This example demonstrates how to use `v.examples` with a string schema to specify valid string examples. ```ts const StringSchema = v.pipe(v.string(), v.examples(['foo', 'bar', 'baz'])); ``` #### Number Schema Example This example shows how to use `v.examples` with a number schema to define valid number examples. ```ts const NumberSchema = v.pipe(v.number(), v.examples([1, 2, 3])); ``` ### Related APIs #### 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 - getExamples - pipe #### Utils - isOfKind - isOfType ``` -------------------------------- ### String Schema with Examples - TypeScript Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/examples/index.mdx Demonstrates how to create a string schema using Valibot's `pipe` and `examples` functions. This schema validates that the input is a string and provides a list of allowed example strings. ```typescript const StringSchema = v.pipe(v.string(), v.examples(['foo', 'bar', 'baz'])); ``` -------------------------------- ### Extract Examples from String and Nested Schemas Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(methods)/getExamples/index.mdx Shows how to extract examples from both simple string schemas and complex nested schemas using the pipe method and examples action. ```typescript const StringSchema = v.pipe(v.string(), v.examples(['foo', 'bar', 'baz'])); const examples = v.getExamples(StringSchema); const NestedSchema = v.pipe( v.string(), v.examples(['foo', 'bar', 'baz']), v.pipe(v.string(), v.examples(['qux', 'quux'])) ); const nestedExamples = v.getExamples(NestedSchema); ``` -------------------------------- ### notSize Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/notSize/index.mdx Examples demonstrating the usage of the notSize action. ```APIDOC ## Examples ### Blob size schema Schema to validate a blob with less ore more then 10 MB. ```ts const BlobSchema = v.pipe( v.blob(), v.notSize(10 * 1024 * 1024, 'The blob must not be 10 MB in size.') ); ``` ### Set size schema Schema to validate a set with less ore more then 8 numbers. ```ts const SetSchema = v.pipe( v.set(number()), v.notSize(8, 'The set must not contain 8 numbers.') ); ``` ``` -------------------------------- ### IMEI Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/imei/index.mdx Example of how to create an IMEI schema using `v.pipe` and `v.imei` for validation. ```APIDOC ## POST /schemas/imei ### Description Demonstrates how to create a schema for validating IMEI strings using Valibot's `pipe` and `imei` functions. This schema ensures that the input is a string and adheres to the IMEI format, with a customizable error message. ### Method POST ### Endpoint /schemas/imei ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **message** (string) - Optional - Custom error message if the input string is not a valid IMEI. ### Request Example ```json { "message": "The imei is badly formatted." } ``` ### Response #### Success Response (200) - **Schema** (object) - The created IMEI validation schema. #### Response Example ```json { "schema": "imei_schema_definition" } ``` ``` -------------------------------- ### Function Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/args/index.mdx Example demonstrating how to use the `args` action to create a schema for a function that transforms a string to a number. ```APIDOC ## POST /examples/function-schema ### Description Example of creating a function schema that transforms a string to a number using the `args` action. ### Method POST ### Endpoint /examples/function-schema ### Parameters #### Request Body - **schema** (object) - Required - The schema for the function. ### Request Example ```json { "schema": { "type": "pipe", "items": [ { "type": "function" }, { "type": "args", "schema": { "type": "tuple", "items": [ { "type": "pipe", "items": [ { "type": "string", "validation": "decimal" } ] } ] } }, { "type": "returns", "schema": { "type": "number" } } ] } } ``` ### Response #### Success Response (200) - **Schema** (object) - The resulting function schema. #### Response Example ```json { "schema": { "type": "pipe", "items": [ { "type": "function" }, { "type": "args", "schema": { "type": "tuple", "items": [ { "type": "pipe", "items": [ { "type": "string", "validation": "decimal" } ] } ] } }, { "type": "returns", "schema": { "type": "number" } } ] } } ``` ``` -------------------------------- ### mac64 Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/mac64/index.mdx Example of how to use the mac64 action within a validation schema. ```APIDOC ## POST /schemas/mac64 ### Description Defines a schema to validate a 64-bit MAC address using the `mac64` action. An optional custom error message can be included. ### Method POST ### Endpoint /schemas/mac64 ### Parameters #### Request Body - **message** (string) - Optional - The error message to display if the validation fails. ### Request Example ```json { "message": "The MAC address is badly formatted." } ``` ### Response #### Success Response (200) - **schema** (object) - The validation schema for a 64-bit MAC address. #### Response Example ```json { "schema": "mac64_schema_object" } ``` ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/open-circle/valibot/blob/main/website/README.md Installs all necessary project dependencies using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Attach and extract AI-readable metadata with examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/blog/(posts)/valibot-v1.2-release-notes/index.mdx Uses the examples() action to attach sample data to schema fields, which can then be retrieved using getExamples() for AI tools or documentation generation. ```typescript import * as v from 'valibot'; const UserSchema = v.object({ id: v.pipe(v.string(), v.uuid(), v.examples(['550e8400-e29b-41d4-a716-446655440000'])), name: v.pipe(v.string(), v.nonEmpty(), v.examples(['Alice Smith', 'Bob Johnson'])), email: v.pipe(v.string(), v.email(), v.examples(['alice@example.com', 'bob@example.com'])), }); const emailExamples = v.getExamples(UserSchema.entries.email); ``` -------------------------------- ### Number Schema with Examples - TypeScript Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/examples/index.mdx Illustrates the creation of a number schema with predefined examples using Valibot. The `pipe` function combines the `number` schema with the `examples` function to enforce that the input is a number and matches one of the provided example numbers. ```typescript const NumberSchema = v.pipe(v.number(), v.examples([1, 2, 3])); ``` -------------------------------- ### Example: Allowed IPs Schema with setAsync Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/setAsync/index.mdx An example demonstrating how to use setAsync to create a schema that validates a set of IP addresses. It pipes together string, IP validation, and an asynchronous check for allowed IPs. ```typescript import { isIpAllowed } from '~/api'; const AllowedIPsSchema = v.setAsync( v.pipeAsync( v.string(), v.ip(), v.checkAsync(isIpAllowed, 'This IP address is not allowed.') ) ); ``` -------------------------------- ### BIC Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/bic/index.mdx An example demonstrating how to use the `bic` action within a Valibot schema for validating BIC strings. ```APIDOC ## POST /schemas/bic ### Description Defines a schema to validate a BIC string using Valibot's `pipe`, `string`, `toUpperCase`, and `bic` actions. ### Method POST ### Endpoint /schemas/bic ### Parameters #### Request Body - **message** (string) - Optional - Custom error message for BIC validation failure. ### Request Example ```json { "message": "The BIC is badly formatted." } ``` ### Response #### Success Response (200) - **schema** (object) - The BIC validation schema. #### Response Example ```json { "schema": { "type": "object", "properties": { "bic": { "type": "string", "description": "A valid BIC" } } } } ``` ``` -------------------------------- ### Allowed IPs Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/setAsync/index.mdx An example demonstrating how to use setAsync in conjunction with other Valibot functions like pipeAsync, string, ip, and checkAsync to create a schema that validates a set of allowed IP addresses. ```APIDOC ## Example: Allowed IPs Schema ### Description Schema to validate a set of allowed IP addresses using `setAsync` and other validation utilities. ### Method N/A (This is a usage example) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { v } from 'valibot'; import { isIpAllowed } from '~/api'; // Assuming isIpAllowed is defined elsewhere const AllowedIPsSchema = v.setAsync( v.pipeAsync( v.string(), v.ip(), v.checkAsync(isIpAllowed, 'This IP address is not allowed.') ) ); ``` ### Response N/A (This is a usage example) ### Response Example N/A ``` -------------------------------- ### Date Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/toDate/index.mdx Example demonstrating how to use the toDate action within a schema to validate a string and transform it into a date. ```APIDOC ## Date Schema Example ### Description This example shows how to create a schema that validates an input as a string and then transforms it into a Date object using the `toDate` action. ### Method Schema Creation ### Endpoint N/A (Client-side schema definition) ### Parameters None ### Request Example ```typescript import * as v from 'valibot'; const DateSchema = v.pipe(v.string(), v.toDate()); ``` ### Response #### Success Response (200) Defines a schema that accepts strings and outputs Date objects. #### Response Example ```json { "schema": "pipe(string(), toDate())" } ``` ``` -------------------------------- ### Email Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/rfcEmail/index.mdx An example demonstrating how to use the `rfcEmail` action within a schema to validate an email string. ```APIDOC ### Email schema Schema to validate an email. ```ts const EmailSchema = v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.rfcEmail('The email is badly formatted.'), v.maxLength(30, 'Your email is too long.') ); ``` ``` -------------------------------- ### Install Valibot from JSR Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/guides/(get-started)/installation/index.mdx Add Valibot to your Node, Deno, or Bun project using JSR. After installation, you can import it into your JavaScript or TypeScript files. ```bash deno add jsr:@valibot/valibot # deno ``` ```bash npx jsr add @valibot/valibot # npm ``` ```bash yarn dlx jsr add @valibot/valibot # yarn ``` ```bash pnpm dlx jsr add @valibot/valibot # pnpm ``` ```bash bunx jsr add @valibot/valibot # bun ``` -------------------------------- ### IPv4 Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/ipv4/index.mdx Example demonstrating how to use the ipv4 action within a Valibot schema to validate an IPv4 address string. ```APIDOC ## POST /schemas/ipv4 ### Description Schema to validate an IPv4 address using the `ipv4` action. ### Method POST ### Endpoint /schemas/ipv4 ### Parameters #### Request Body - **message** (string) - Optional - Custom error message if the input is not a valid IPv4 address. ### Request Example ```json { "message": "The IP address is badly formatted." } ``` ### Response #### Success Response (200) - **schema** (object) - The IPv4 validation schema. #### Response Example ```json { "schema": "ipv4_validation_schema" } ``` ``` -------------------------------- ### 48-bit MAC Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/mac48/index.mdx Example of how to use the mac48 action within a validation schema to ensure a string is a valid 48-bit MAC address. ```APIDOC ## POST /schemas/mac48/schema.ts ### Description Defines a schema to validate a 48-bit MAC address using the `mac48` action. It first ensures the input is a string and then applies the MAC address format validation. ### Method POST ### Endpoint /schemas/mac48/schema.ts ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "schema": "Mac48Schema" } ``` ### Response #### Success Response (200) - **Schema** (object) - The defined MAC address schema. #### Response Example ```json { "schema": { "type": "string", "validation": "mac48", "message": "The MAC address is badly formatted." } } ``` ``` -------------------------------- ### getTitle Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(methods)/getTitle/index.mdx Illustrates how to use the getTitle method with different schema configurations. ```APIDOC # getTitle Examples ## Get title of schema Get the title of a username schema. ```ts import * as v from 'valibot'; const UsernameSchema = v.pipe( v.string(), v.regex(/^[a-z0-9_-]{4,16}$/iu), v.title('Username'), v.description( 'A username must be between 4 and 16 characters long and can only contain letters, numbers, underscores and hyphens.' ) ); const title = v.getTitle(UsernameSchema); // 'Username' ``` ## Overriding inherited titles Get the title of a Gmail schema with an overridden title. ```ts import * as v from 'valibot'; const EmailSchema = v.pipe(v.string(), v.email(), v.title('Email')); const GmailSchema = v.pipe( EmailSchema, v.endsWith('@gmail.com'), v.title('Gmail') ); const title = v.getTitle(GmailSchema); // 'Gmail' ``` ``` -------------------------------- ### trimStart Transformation Action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/trimStart/index.mdx API documentation for the trimStart function used to trim whitespace from the start of strings. ```APIDOC ## trimStart ### Description Creates a trim start transformation action that removes whitespace from the beginning of a string. ### Method Transformation Action ### Endpoint v.trimStart() ### Parameters None ### Request Example ```ts const Action = v.trimStart(); ``` ### Response #### Success Response - **Action** (Object) - A transformation action that can be used within a pipe. #### Response Example ```ts const StringSchema = v.pipe(v.string(), v.trimStart()); ``` ``` -------------------------------- ### MaxBytesSchema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/maxBytes/index.mdx Demonstrates how to use the maxBytes action within a Valibot schema pipeline. This example creates a schema that validates a string, ensuring it does not exceed 64 bytes, and provides a custom error message if the validation fails. ```typescript const MaxBytesSchema = v.pipe( v.string(), v.maxBytes(64, 'The string must not exceed 64 bytes.') ); ``` -------------------------------- ### Install Valibot from npm Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/guides/(get-started)/installation/index.mdx Add Valibot to your Node or Bun project using your preferred package manager. After installation, you can import it into your JavaScript or TypeScript files. ```bash npm install valibot # npm ``` ```bash yarn add valibot # yarn ``` ```bash pnpm add valibot # pnpm ``` ```bash bun add valibot # bun ``` -------------------------------- ### Shopping Items Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/mapAsync/index.mdx An example demonstrating the use of mapAsync to create a schema for validating shopping items. It includes asynchronous verification of usernames as keys and ensures the number of items purchased as values is non-negative. ```typescript import { isUserVerified } from '~/api'; import * as v from 'valibot'; const ShoppingItemsSchema = v.mapAsync( v.pipeAsync( v.string(), v.checkAsync(isUserVerified, 'The username is not allowed to shop.') ), v.pipe(v.number(), v.minValue(0)) ); ``` -------------------------------- ### Example Usage of Description Action - Valibot TS Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/description/index.mdx Demonstrates how to use the `description` action within a Valibot schema pipeline. This example creates a 'UsernameSchema' that includes a string validation, a regex for format, a title, and a detailed description explaining the username requirements. ```typescript const UsernameSchema = v.pipe( v.string(), v.regex(/^[a-z0-9_-]{4,16}$/iu), v.title('Username'), v.description( 'A username must be between 4 and 16 characters long and can only contain letters, numbers, underscores and hyphens.' ) ); ``` -------------------------------- ### ISO Timestamp Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/isoTimestamp/index.mdx An example demonstrating how to use the isoTimestamp action within a Valibot schema to validate a string as an ISO timestamp. ```APIDOC ## ISO Timestamp Schema Example ### Description This example shows how to create a Valibot schema that uses `v.string()` and `v.isoTimestamp()` to validate if an input string is a correctly formatted ISO timestamp. ### Method Schema Definition ### Endpoint N/A ### Parameters None ### Request Example ```ts const IsoTimestampSchema = v.pipe( v.string(), v.isoTimestamp('The timestamp is badly formatted.') ); ``` ### Response #### Success Response (200) Indicates that the provided string is a valid ISO timestamp. #### Response Example ```json { "valid": true } ``` ``` -------------------------------- ### Install Valibot Agent Skill Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/guides/(get-started)/installation/index.mdx Install the Valibot agent skill for AI agents by running this command in your terminal. More information is available on GitHub. ```bash npx skills add open-circle/agent-skills --skill valibot ``` -------------------------------- ### Hash Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/hash/index.mdx An example demonstrating how to create a schema to validate a hash using the `hash` action. This schema first ensures the input is a string and then validates it against specified hash types (MD5, SHA1) with a custom error message. ```typescript const HashSchema = v.pipe( v.string(), v.hash(['md5', 'sha1'], 'The specified hash is invalid.') ); ``` -------------------------------- ### ISO Time Schema Validation Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/isoTime/index.mdx An example demonstrating how to create a schema using Valibot's pipe and isoTime functions to validate if a string is a correctly formatted ISO time. It includes a custom error message. ```typescript const IsoTimeSchema = v.pipe( v.string(), v.isoTime('The time is badly formatted.') ); ``` -------------------------------- ### Parse and validate JSON Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/parseJson/index.mdx Example demonstrating how to parse a JSON string and then validate the parsed result using Valibot's pipe and object schema. ```APIDOC ## Example: Parse and validate JSON ### Description This example shows how to use `v.pipe` with `v.string()` and `v.parseJson()` to parse a JSON string, followed by `v.object()` to validate the structure of the parsed JSON. ### Code ```typescript const StringifiedObjectSchema = v.pipe( v.string(), v.parseJson(), v.object({ key: v.string() }) ); ``` ``` -------------------------------- ### IPv4 Schema Validation Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/ipv4/index.mdx An example demonstrating how to create a schema to validate an IPv4 address using Valibot's `pipe`, `string`, and `ipv4` functions. It pipes a string validation with the IPv4 format check. ```typescript const Ipv4Schema = v.pipe( v.string(), v.ipv4('The IP address is badly formatted.') ); ``` -------------------------------- ### Schema Tree Traversal Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/guides/(advanced)/integrate-valibot/index.mdx Demonstrates how to traverse a Valibot schema tree to extract information, such as default values. ```APIDOC ## Schema Tree Traversal Because schemas are plain objects, we can walk a schema tree by reading its properties (see [Runtime properties](#runtime-properties)). When traversing a piped schema, read the `pipe` tuple — its first item is the root schema and subsequent items are pipe actions or nested schemas. Here is a simplified example inspired by `getDefaults` that extracts deeply nested default values from object and tuple schemas: ```ts import * as v from 'valibot'; function getDefaults< TSchema extends | v.BaseSchema> | v.ObjectSchema | undefined> | v.TupleSchema | undefined>, >(schema: TSchema): v.InferDefaults { // If it is an object schema, return defaults of entries if ('entries' in schema) { const object: Record = {}; for (const key in schema.entries) { object[key] = getDefaults(schema.entries[key]); } return object; } // If it is a tuple schema, return defaults of items if ('items' in schema) { return schema.items.map(getDefaults); } // Otherwise, return default or `undefined` return v.getDefault(schema); } ``` ``` -------------------------------- ### Example: Cart Item Schema with checkAsync Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/checkAsync/index.mdx Demonstrates how to use checkAsync within a pipeAsync to create a schema for validating cart items. This example includes asynchronous fetching of product data to check item availability against the required quantity. ```typescript import { getProductItem } from '~/api'; const CartItemSchema = v.pipeAsync( v.object({ itemId: v.pipe(v.string(), v.regex(/^[a-z0-9]{10}$/i)), quantity: v.pipe(v.number(), v.minValue(1)), }), v.checkAsync(async (input) => { const productItem = await getProductItem(input.itemId); return productItem?.quantity >= input.quantity; }, 'The required quantity is greater than available.') ); ``` -------------------------------- ### Validate HTTPS URL with startsWith Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/startsWith/index.mdx Demonstrates how to use the startsWith action within a Valibot pipe to validate if a string is a URL that starts with 'https://'. This example combines string, URL, and startsWith validations. ```typescript const HttpsUrlSchema = v.pipe(v.string(), v.url(), v.startsWith('https://')); ``` -------------------------------- ### Octal Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/octal/index.mdx An example of how to create a schema using the 'octal' validation action. This schema first ensures the input is a string and then validates if it's a correctly formatted octal number, with a custom error message. ```typescript const OctalSchema = v.pipe( v.string(), v.octal('The octal is badly formatted.') ); ``` -------------------------------- ### Build Core Library Source: https://github.com/open-circle/valibot/blob/main/packages/i18n/README.md Navigate to the core library directory and build it. ```bash cd ./library && pnpm build ``` -------------------------------- ### Literal Schema Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/literal/index.mdx Illustrates various use cases for creating literal schemas with different data types. ```APIDOC ## GET /api/users/{id} ### Description Provides examples of creating literal schemas for string, number, and boolean values. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **user** (object) - Details of the requested user. #### Response Example ```json { "user": { "id": "123", "name": "John Doe" } } ``` ``` -------------------------------- ### Initialize trimStart Action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/trimStart/index.mdx Demonstrates how to instantiate the trimStart transformation action using the Valibot library. ```typescript const Action = v.trimStart(); ``` -------------------------------- ### String Schema Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/string/index.mdx Illustrates practical use cases of the string schema combined with other validation methods. ```APIDOC ## String Schema Use Cases ### Email Schema Validates if the input is a properly formatted email address with length constraints. ```typescript const EmailSchema = v.pipe( v.string(), v.nonEmpty('Please enter your email.'), v.email('The email is badly formatted.'), v.maxLength(30, 'Your email is too long.') ); ``` ### Password Schema Validates a password against complexity requirements including length, lowercase, uppercase, and numeric characters. ```typescript const PasswordSchema = v.pipe( v.string(), v.minLength(8, 'Your password is too short.'), v.maxLength(30, 'Your password is too long.'), v.regex(/[a-z]/, 'Your password must contain a lowercase letter.'), v.regex(/[A-Z]/, 'Your password must contain a uppercase letter.'), v.regex(/[0-9]/, 'Your password must contain a number.') ); ``` ### URL Schema Validates if the input is a correctly formatted URL. ```typescript const UrlSchema = v.pipe( v.string('A URL must be string.'), v.url('The URL is badly formatted.') ); ``` ``` -------------------------------- ### nonNullish Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/nonNullish/index.mdx Examples demonstrating the usage of the nonNullish schema function. ```APIDOC ## Examples ### Non nullish string Schema that does not accept `null` and `undefined`. ```ts const NonNullishStringSchema = v.nonNullish(v.nullish(v.string())); ``` ### Unwrap non nullish Use `unwrap` to undo the effect of `nonNullish`. ```ts const NonNullishNumberSchema = v.nonNullish(v.nullish(v.number())); const NullishNumberSchema = v.unwrap(NonNullishNumberSchema); ``` ``` -------------------------------- ### Initialize returns action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/returns/index.mdx Demonstrates the basic syntax for creating a returns action by passing a schema to the v.returns function. ```typescript const Action = v.returns(schema); ``` -------------------------------- ### Function Schema Example - TypeScript Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/args/index.mdx An example demonstrating how to use the args action within a Valibot schema to transform function arguments. This specific example transforms a string input to a number. ```typescript const FunctionSchema = v.pipe( v.function(), v.args(v.tuple([v.pipe(v.string(), v.decimal())])), v.returns(v.number()) ); ``` -------------------------------- ### any Schema Creation Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/any/index.mdx Demonstrates how to create an `any` schema using the `valibot` library. ```APIDOC ## any Schema ### Description Creates a schema that accepts any type of value. This is generally not recommended; `unknown` should be preferred. ### Returns - `Schema` - The created schema object. ### Example ```ts import * as v from 'valibot'; const Schema = v.any(); ``` ``` -------------------------------- ### BigInt Validation Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/bigint/index.mdx Examples of using bigint with pipeable actions to enforce constraints. ```APIDOC ## BigInt Constraints ### Force Minimum ```ts const MinBigintSchema = v.pipe(v.bigint(), v.toMinValue(10n)); ``` ### Validate Maximum ```ts const MaxBigintSchema = v.pipe(v.bigint(), v.maxValue(999n)); ``` ``` -------------------------------- ### nonNullishAsync Usage Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/nonNullishAsync/index.mdx An example demonstrating the usage of nonNullishAsync with other Valibot schema functions. ```APIDOC ## Example: Allowed country schema ### Description Schema to check if a string matches one of the allowed country names, ensuring the input is not null or undefined. ### Code ```typescript import { v } from 'valibot'; import { isAllowedCountry } from '~/api'; // Assuming isAllowedCountry is imported from an API module const AllowedCountrySchema = v.nonNullishAsync( v.nullishAsync( v.pipeAsync( v.string(), v.nonEmpty(), v.checkAsync(isAllowedCountry) ) ) ); ``` ``` -------------------------------- ### Emoji Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/emoji/index.mdx Example of how to use the emoji validation action within a schema. ```APIDOC ## Emoji Schema Example ### Description Schema to validate an emoji using the `emoji` validation action. ### Method N/A (This is a schema definition) ### Endpoint N/A ### Parameters None ### Request Example ```ts const EmojiSchema = v.pipe( v.string(), v.emoji('Please provide a valid emoji.') ); ``` ### Response #### Success Response (200) Validates if the input string is a valid emoji. #### Response Example ```json { "valid": true } ``` ``` -------------------------------- ### Basic Usage of forwardAsync Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/forwardAsync/index.mdx Demonstrates the basic syntax for initializing a forwardAsync action with a target path. ```typescript const Action = v.forwardAsync(action, path); ``` -------------------------------- ### Create a basic file schema Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/file/index.mdx Demonstrates the basic instantiation of a file schema using Valibot. It accepts an optional custom error message. ```typescript const Schema = v.file(message); ``` -------------------------------- ### Example: Profile Table Schema with Metadata - Valibot Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/metadata/index.mdx Demonstrates how to create a schema for a profile table using Valibot and attach metadata. The metadata includes table name, primary key, and indexes, which can be used by other tools or services. ```typescript const ProfileTableSchema = v.pipe( v.object({ username: v.pipe(v.string(), v.nonEmpty()), email: v.pipe(v.string(), v.email()), avatar: v.pipe(v.string(), v.url()), description: v.pipe(v.string(), v.maxLength(500)), }), v.metadata({ table: 'profiles', primaryKey: 'username', indexes: ['email'], }) ); ``` -------------------------------- ### Array Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/includes/index.mdx Example of using the includes action to validate that an array contains a specific string. ```APIDOC ## Array Schema Example ### Description Schema to validate that an array contains a specific string using the `includes` action. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "example": "const ArraySchema = v.pipe(v.array(v.string()), v.includes('foo', 'The array must contain \"foo\".'))" } ``` ### Response N/A ``` -------------------------------- ### String Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/includes/index.mdx Example of using the includes action to validate that a string contains a specific substring. ```APIDOC ## String Schema Example ### Description Schema to validate that a string contains a specific substring using the `includes` action. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "example": "const StringSchema = v.pipe(v.string(), v.includes('foo', 'The string must contain \"foo\".'))" } ``` ### Response N/A ``` -------------------------------- ### Build Project Source: https://github.com/open-circle/valibot/blob/main/CLAUDE.md Builds all packages in the monorepo for publishing. ```bash pnpm build ``` -------------------------------- ### Build Valibot Library Source: https://github.com/open-circle/valibot/blob/main/website/README.md Navigates to the library directory and compiles the Valibot library using pnpm. ```bash cd ./library && pnpm build ``` -------------------------------- ### Valibot Graphemes Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/graphemes/index.mdx An example demonstrating how to use the `v.graphemes` action within a Valibot schema pipeline. This specific example creates a schema that validates if a string contains exactly 8 graphemes, providing a custom error message if the condition is not met. ```typescript const GraphemesSchema = v.pipe( v.string(), v.graphemes(8, 'Exactly 8 graphemes are required.') ); ``` -------------------------------- ### Create an Any Schema Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/any/index.mdx This snippet demonstrates how to create a basic `any` schema. Use this when you need to accept any value, but prefer `unknown` for better type safety. ```typescript const Schema = v.any(); ``` -------------------------------- ### Pascal case string example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/toPascalCase/index.mdx Example demonstrating how to use the `toPascalCase` action within a validation pipe to transform a string to PascalCase. ```APIDOC ## Pascal case string Schema that transforms a string to pascal case. ### Usage ```ts const StringSchema = v.pipe(v.string(), v.toPascalCase()); ``` ``` -------------------------------- ### Async Product Function Schema with argsAsync Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/argsAsync/index.mdx Demonstrates how to use argsAsync in conjunction with other Valibot async utilities (pipeAsync, function, returnsAsync) to create a schema for an asynchronous function that fetches and returns product details by ID. It validates the input product ID and the structure of the returned product object. ```typescript import { isValidProductId } from '~/api'; const ProductFunctionSchema = v.pipeAsync( v.function(), v.argsAsync( v.tupleAsync([v.pipeAsync(v.string(), v.checkAsync(isValidProductId))]) ), v.returnsAsync( v.pipeAsync( v.promise(), v.awaitAsync(), v.object({ id: v.string(), name: v.string(), price: v.number(), }) ) ) ); ``` -------------------------------- ### Graphemes Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/graphemes/index.mdx Example of how to use the graphemes action within a Valibot schema to validate a string with exactly 8 graphemes. ```APIDOC ## Example: Graphemes Schema ### Description Schema to validate a string with 8 graphemes. ### Code ```typescript import * as v from 'valibot'; const GraphemesSchema = v.pipe( v.string(), v.graphemes(8, 'Exactly 8 graphemes are required.') ); ``` ### Usage This schema can be used with Valibot's validation functions to ensure a string contains exactly 8 graphemes. ``` -------------------------------- ### Initialize Valibot Parser Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(methods)/parser/index.mdx Demonstrates how to instantiate a parser function using a schema and optional configuration. ```typescript const parser = v.parser(schema, config); ``` -------------------------------- ### Filter Duplicate Items Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/filterItems/index.mdx Example demonstrating how to use `filterItems` to create a schema that filters out duplicate items from an array of strings. ```APIDOC ## Example: Filter Duplicate Items ### Description This example shows how to use the `filterItems` action within a `pipe` to create a schema that effectively removes duplicate string elements from an array. ### Code ```typescript const FilteredArraySchema = v.pipe( v.array(v.string()), v.filterItems((item, index, array) => array.indexOf(item) === index) ); ``` ### Explanation The `v.array(v.string())` part defines an array of strings. The `v.filterItems` action is then applied, using a callback function that checks if the first occurrence of the `item` in the `array` matches the current `index`. If they match, it means the item is not a duplicate (or it's the first instance of a duplicate), and it's kept. Otherwise, it's filtered out. ``` -------------------------------- ### Array Schema Examples Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(schemas)/array/index.mdx Demonstrates various ways to use the `array` schema, including validating string arrays, object arrays, array length, and array content. ```APIDOC ## Examples for Array Schema ### String array schema Schema to validate an array of strings. ```ts const StringArraySchema = v.array(v.string(), 'An array is required.'); ``` ### Object array schema Schema to validate an array of objects. ```ts const ObjectArraySchema = v.array(v.object({ key: v.string() })); ``` ### Validate length Schema that validates the length of an array. ```ts const ArrayLengthSchema = v.pipe( v.array(v.number()), v.minLength(1), v.maxLength(3) ); ``` ### Validate content Schema that validates the content of an array. ```ts const ArrayContentSchema = v.pipe( v.array(v.string()), v.includes('foo'), v.excludes('bar') ); ``` ``` -------------------------------- ### Basic usage of pick method Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(methods)/pick/index.mdx Demonstrates how to use the pick method to create a new schema from an existing object schema by selecting specific keys. ```typescript const PickedSchema = v.pick( v.object({ key1: string(), key2: number(), key3: boolean(), }), ['key1', 'key3'] ); // { key1: string; key3: boolean } ``` -------------------------------- ### Parse JSON with reviver Function Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/parseJson/index.mdx Example demonstrating how to parse a JSON string using a reviver function to transform values during parsing. ```APIDOC ## Example: Parse JSON with reviver ### Description This example illustrates using `v.parseJson()` with a `reviver` function. The reviver function is applied to each key-value pair during JSON parsing, allowing for value transformations. ### Code ```typescript const StringifiedObjectSchema = v.pipe( v.string(), v.parseJson({ reviver: (key, value) => typeof value === 'string' ? value.toUpperCase() : value, }), v.object({ key: v.string() }) ); ``` ``` -------------------------------- ### Initialize everyItem Action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/everyItem/index.mdx Demonstrates the basic syntax for creating an everyItem validation action using Valibot generics and parameters. ```typescript const Action = v.everyItem(requirement, message); ``` -------------------------------- ### Recursive Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/lazyAsync/index.mdx Example demonstrating the use of lazyAsync to create a recursive schema for validating a list of transactions, including a self-referencing 'next' property. ```APIDOC ## Recursive Transaction Schema Example ### Description This example shows how to define a recursive schema for transactions using `lazyAsync`. It validates a `transactionId` and a `next` transaction, which can be null. Due to TypeScript limitations with recursive types, `GenericSchemaAsync` is used to explicitly define the types. ### Code ```typescript import { isTransactionValid } from '~/api'; type Transaction = { transactionId: string; next: Transaction | null; }; const TransactionSchema: v.GenericSchemaAsync = v.objectAsync({ transactionId: v.pipeAsync( v.string(), v.uuid(), v.checkAsync(isTransactionValid, 'The transaction is not valid.') ), next: v.nullableAsync(v.lazyAsync(() => TransactionSchema)), }); ``` ``` -------------------------------- ### Initialize trimEnd Action Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/trimEnd/index.mdx Demonstrates how to instantiate the trimEnd action using the Valibot library. This action returns a transformation object that can be applied to string inputs. ```typescript const Action = v.trimEnd(); ``` -------------------------------- ### ExamplesAction Definition Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(types)/ExamplesAction/index.mdx Details the structure and properties of the ExamplesAction metadata action. ```APIDOC ## ExamplesAction ### Description Defines metadata for examples associated with a schema. This action allows developers to attach example values to their validation logic. ### Generics - **TInput** - The input type of the schema. - **TExamples** - The type of the examples metadata. ### Definition - **type** (string) - The identifier for the action type. - **reference** (function) - The reference to the metadata action. - **examples** (TExamples) - The actual example data provided. ### Related APIs - **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**: getExamples, pipe. - **Actions**: examples ``` -------------------------------- ### Basic Config Usage Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(methods)/config/index.mdx Demonstrates the basic usage of the `config` method to create a schema with a custom error message for the entire pipeline. ```typescript const Schema = v.object({ email: v.config( v.pipe(v.string(), v.trim(), v.email(), v.endsWith('@example.com')), { message: 'The email does not conform to the required format.' } ), // ... }); ``` -------------------------------- ### Add User Schema Example with nonOptionalAsync Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/nonOptionalAsync/index.mdx An example demonstrating the use of nonOptionalAsync within an object schema to validate user details, including asynchronous checks for group presence. ```typescript import { isGroupPresent } from '~/api'; const AddUserSchema = v.objectAsync({ groupId: v.nonOptionalAsync( // Assume this schema is from a different file and reused here. v.optionalAsync( v.pipeAsync( v.string(), v.uuid(), v.checkAsync( isGroupPresent, 'The group is not present in the database.' ) ) ) ), userEmail: v.pipe(v.string(), v.email()), }); ``` -------------------------------- ### Words Schema Example Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(actions)/words/index.mdx An example of how to create a schema using the `words` action to validate that a string contains exactly 3 words. This demonstrates chaining `v.string()`, `v.words()`, and `v.pipe()`. ```typescript import { v } from 'valibot'; const WordsSchema = v.pipe( v.string(), v.words('en', 3, 'Exactly 3 words are required.') ); ``` -------------------------------- ### Union Schema Example with lazyAsync Source: https://github.com/open-circle/valibot/blob/main/website/src/routes/api/(async)/lazyAsync/index.mdx Example illustrating how lazyAsync can be used to create a schema that validates an object which could represent either an email or a username, with specific validation logic for each case. ```APIDOC ## Email or Username Schema Example ### Description This example demonstrates using `lazyAsync` to create a schema that validates an object containing either an email or a username. The schema dynamically determines the expected structure based on the `type` property of the input. Note that `unionAsync` or `variantAsync` are generally preferred for such scenarios. ### Code ```typescript import { isEmailPresent, isUsernamePresent } from '~/api'; const EmailOrUsernameSchema = v.lazyAsync((input) => { if (input && typeof input === 'object' && 'type' in input) { switch (input.type) { case 'email': return v.objectAsync({ type: v.literal('email'), email: v.pipeAsync( v.string(), v.email(), v.checkAsync( isEmailPresent, 'The email is not present in the database.' ) ), }); case 'username': return v.objectAsync({ type: v.literal('username'), username: v.pipeAsync( v.string(), v.nonEmpty(), v.checkAsync( isUsernamePresent, 'The username is not present in the database.' ) ), }); } } return v.never(); }); ``` ```