Skip to main content

API

ClassValidationPipe

Validates values using class-validator decorators and class-transformer for type conversion. The pipe automatically extracts parameter type metadata and validates incoming data against the decorated class properties.

ClassValidationPipe can be registered as a global pipe: adapter.useGlobalPipe(new ClassValidationPipe()). This way, controller parameters with decorated classes are automatically validated.

Example: register a ClassValidationPipe globally

import { ClassValidationPipe } from '@inversifyjs/class-validation';
import { InversifyExpressHttpAdapter } from '@inversifyjs/http-express';
import { InversifyValidationErrorFilter } from '@inversifyjs/http-validation';
import { Container } from 'inversify';

const container: Container = new Container();

const adapter: InversifyExpressHttpAdapter = new InversifyExpressHttpAdapter(
container,
{ logger: true },
);
adapter.useGlobalFilters(InversifyValidationErrorFilter);
adapter.useGlobalPipe(new ClassValidationPipe());

Using class-validator decorators

To validate request parameters, create classes with class-validator decorators and use them as parameter types in your controller methods. The ClassValidationPipe will automatically validate and transform the data.

On validation failure, an InversifyValidationError is thrown and can be converted to a Bad Request HTTP response by InversifyValidationErrorFilter.

Example: validate request body with class-validator

import { Body, Controller, Post } from '@inversifyjs/http-core';
import { IsString } from 'class-validator';

class Message {
@IsString()
public readonly content!: string;
}

@Controller('/messages')
export class MessageController {
@Post()
public async createMessage(
@Body()
message: Message,
): Promise<Message> {
return message;
}
}

Available Validation Decorators

Class-validator provides many built-in validation decorators. For a complete list of available decorators, see the class-validator documentation.