Getting started
Inversify Validation is a powerful set of tools to create validation flows on top of InversifyJS. It provides decorators and utilities to define validation schemas, apply them to your classes, and handle validation errors gracefully.
This docs focusess on validation in the context of HTTP applications, but the validation tools can be used in any context a Pipe can be used.
Install dependencies
Given a HTTP adapter of your choice already set up, using validation tools is straightforward:
Begin by installing the validation package of your choice along with its peer dependencies:
- Zod (Standard schema)
- Ajv
- class-validator
npm install zod @inversifyjs/standard-schema-validation
npm install ajv @inversifyjs/ajv-validation
npm install class-validator class-transformer @inversifyjs/class-validation
Make sure to enable the Experimental Decorators and Emit Decorator Metadata options in your tsconfig.json.
Install integration package
Validation tools are designed to work outside HTTP context. In order to use them in an HTTP application, you need to install the appropriate package.
npm install @inversifyjs/http-validation
Configure server
In order to enable validation in your application, you need to configure the server:
- Use the specific validator error pipe. If we take the previous example, we need to use a
StandardSchemaValidationPipe, for Zod is integrated via Standard Schema integration. - Use the
ValidationErrorFilterto handle validation errors. This error filter provided by the@inversifyjs/http-validationpackage catches validation errors in order to send Bad Request HTTP responses on top of them.
const adapter: InversifyExpressHttpAdapter = new InversifyExpressHttpAdapter(
container,
{
logger: true,
useCookies: true,
},
);
adapter.useGlobalFilters(ValidationErrorFilter);
adapter.useGlobalPipe(new StandardSchemaValidationPipe());
Configure controller
After configuring the server, just apply the validation decorators to your controller routes. Below is a basic example of setting up a controller to validate a request body.
import { Body, Controller, Post } from '@inversifyjs/http-core';
import { ValidateStandardSchemaV1 } from '@inversifyjs/standard-schema-validation';
import zod from 'zod';
interface Message {
content: string;
}
@Controller('/messages')
export class MessageController {
@Post()
public async createMessage(
@Body()
@ValidateStandardSchemaV1(
zod.object({ content: zod.string().max(100) }).strict(),
)
message: Message,
): Promise<Message> {
return message;
}
}