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 InversifyClassValidationError (a subclass of InversifyValidationError) is thrown with an errors field containing the raw class-validator ValidationError[]. It 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.
Customizing validation error responses
InversifyValidationErrorFilter returns { message } by default. When frontends need field-level errors, catch InversifyClassValidationError and map its errors field into the response body you want:
import { InversifyClassValidationError } from '@inversifyjs/class-validation';
import {
BadRequestHttpResponse,
CatchError,
type ErrorFilter,
} from '@inversifyjs/http-core';
import { InversifyValidationErrorKind } from '@inversifyjs/validation-common';
import { type ValidationError } from 'class-validator';
function mapClassValidationErrors(
errors: ValidationError[],
): Record<string, string> {
const result: Record<string, string> = {};
for (const error of errors) {
const message: string | undefined =
error.constraints === undefined
? undefined
: Object.values(error.constraints)[0];
if (message !== undefined) {
result[error.property] = message;
}
Object.assign(result, mapClassValidationErrors(error.children ?? []));
}
return result;
}
@CatchError(InversifyClassValidationError)
export class CustomClassValidationErrorFilter implements ErrorFilter<InversifyClassValidationError> {
public catch(error: InversifyClassValidationError): never {
switch (error.kind) {
case InversifyValidationErrorKind.validationFailed:
throw new BadRequestHttpResponse(
{
errors: mapClassValidationErrors(error.errors ?? []),
message: 'Validation failed',
success: false,
},
error.message,
{
cause: error,
},
);
default:
throw new Error(error.message, {
cause: error,
});
}
}
}
Register the filter instead of (or in addition to) the built-in one:
adapter.useGlobalFilters(CustomClassValidationErrorFilter);
That yields responses like:
{
"success": false,
"message": "Validation failed",
"errors": {
"firstName": "First name is required",
"lastName": "Last name is required"
}
}