new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Hono · all subjects

validation

20 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Manual validator import and basic usage

The validator is imported from 'hono/validator' using `import { validator } from 'hono/validator'`. To validate form data, pass 'form' as the first argument and a callback function as the second argument. In the callback, validate the value and return the validated values. The validator can be used as middleware.

Manual validator callback signature

The validator callback function receives two parameters: value (the data to validate) and c (the context object). The callback should validate the value and return either the validated data or an error response using context methods like c.text().

Retrieve validated data in handler

Within a route handler, retrieve validated data using c.req.valid('form') where 'form' is the validation target. For example, `const { body } = c.req.valid('form')` retrieves the body field from form validation.

Validation targets

Validation targets include: json, query, header, param, and cookie. Each can be validated separately using the validator middleware.

JSON and form validation require content-type header

When validating json or form data, the request must contain a matching content-type header (such as 'Content-Type: application/json' for json). Without the correct header, the request body will not be parsed and the callback will receive an empty object. When testing with app.request(), the content-type header must be explicitly set in the headers option.

Header validation requires lowercase header names

When validating headers, use lowercase header names as keys. For example, to validate the 'Idempotency-Key' header, use 'idempotency-key' as the key in the validation callback. Using uppercase or mixed-case header names will result in undefined values.

Multiple validators on single route

You can use multiple validator middlewares on a single route to validate different parts of the request. For example, separate validators can be applied for param, query, and json validation in sequence.

Manual validator with Zod example

You can use Zod for validation by defining a schema with z.object(), then calling schema.safeParse(value) in the validator callback. If parsing fails, return an error response. If successful, return parsed.data.

Zod Validator Middleware import

The Zod Validator Middleware is imported from '@hono/zod-validator' using `import { zValidator } from '@hono/zod-validator'`. It is installed via npm, yarn, pnpm, or bun.

zValidator middleware usage

The zValidator middleware is used as follows: `zValidator('form', z.object({ body: z.string() }))`. Pass the validation target (like 'form', 'json', etc.) as the first argument and the Zod schema as the second argument. Validated data is retrieved with `c.req.valid('form')`.

Standard Schema Validator Middleware

The Standard Schema Validator Middleware (@hono/standard-validator) provides a common interface for any Standard Schema-compatible validation library. It allows using Zod, Valibot, ArkType, and other validation libraries with consistent type safety through a single sValidator middleware.

sValidator middleware import

The Standard Schema Validator Middleware is imported from '@hono/standard-validator' using `import { sValidator } from '@hono/standard-validator'`.

sValidator with Zod example

Zod can be used with sValidator by importing both Zod and sValidator, defining a schema with z.object(), and using sValidator as middleware: `app.post('/author', sValidator('json', schema), (c) => { const data = c.req.valid('json') })`.

sValidator with Valibot example

Valibot can be used with sValidator by importing both Valibot and sValidator, defining a schema with v.object(), and using sValidator as middleware: `app.post('/author', sValidator('json', schema), (c) => { const data = c.req.valid('json') })`.

sValidator with ArkType example

ArkType can be used with sValidator by importing both ArkType and sValidator, defining a schema with type({ name: 'string', age: 'number' }), and using sValidator as middleware: `app.post('/author', sValidator('json', schema), (c) => { const data = c.req.valid('json') })`.

Validator middleware packages available

Third-party validator middleware for Hono includes: Ajv Validator, ArkType Validator, Class Validator, Conform Validator, Effect Schema Validator, Standard Schema Validator, TypeBox Validator, Typia Validator, unknownutil Validator, Valibot Validator, and Zod Validator.

Custom error handling with validator callback

When using a validator like zValidator, you can pass a callback function as the third parameter that receives (result, c) arguments. The result object has a success property. If validation fails (result.success is false), you can return a custom response from the callback, such as c.text('Invalid!', 400).

Zod validator syntax for Hono

Use zValidator from @hono/zod-validator with the signature: zValidator(location, schema, callbackFunction). The location parameter specifies where to validate (e.g., 'json'). The schema is a Zod z.object() defining the expected structure. The callback is optional and receives (result, c) for custom error handling.

Supported validator libraries in Hono

Hono supports multiple validator libraries including Zod Validator, Valibot Validator, Typebox Validator, and Typia Validator. Each has its own package and can be used with similar approaches for validation and error handling.

Validator error handling example with Zod

The following example demonstrates error handling with zValidator: when validation fails, the callback checks result.success and returns c.text('Invalid!', 400) to send a 400 response. If validation succeeds, the handler accesses the data via c.req.valid('json') with proper TypeScript typing for name (string) and age (number) fields defined in the schema.

Give your agent this brain