Skip to content

Custom Validation with class-validator

Sometimes the built-in tsoa-next validator is not enough for an application-specific workflow. In that case you can attach your own validation middleware, for example with class-validator. Relevant API reference: @Middlewares, ValidateError, @Body, @Post, and @SuccessResponse.

This chapter shows a middleware-based class-validator approach for Express.

The @Middlewares decorator accepts middleware functions as positional arguments:

ts
@Middlewares(validateBody(RequestClass))

Install class-validator package

Install class-validator and class-transformer as described in their repos:

https://github.com/typestack/class-transformer

https://github.com/typestack/class-validator

Write custom middleware

The example validation middleware using class-validator:

ts
import { ClassConstructor, plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { NextFunction, Request, Response } from 'express';
import { ValidateError } from 'tsoa-next';

export function validateBody<T extends object>(targetClass: ClassConstructor<T>) {
   return async (req: Request, _res: Response, next: NextFunction) => {
      const instance = plainToInstance(targetClass, req.body);
      const errors = validateSync(instance, {
         forbidUnknownValues: true,
         validationError: {
            target: false
         }
      });
      const fieldsErrors: { [name: string]: { message: string; value: string } } = {};

      if (errors.length > 0) {
         errors.forEach(error => {
            if (error.constraints) {
               fieldsErrors[error.property] = {
                  message: Object.values(error.constraints).join(', '),
                  value: error.value
               };
            }
            if (error.children) {
               error.children.forEach(errorNested => {
                  if (errorNested.constraints) {
                     fieldsErrors[errorNested.property] = {
                        message: Object.values(errorNested.constraints!).join(', '),
                        value: errorNested.value
                     };
                  }
               })
            }
         });
         next(new ValidateError(fieldsErrors, 'Validation failed'));
         return;
      }
      next();
   };
}

Annotate a request class with class-validator

ts
import { Length } from 'class-validator'

class RequestClass {
  @Length(1, 2000)
  public text!: string
}

Usage in a controller

ts
import {
  Body,
  Controller,
  Middlewares,
  Post,
  Route,
  SuccessResponse,
} from 'tsoa-next'
import { validateBody } from '../middleware/ValidationMiddleware'

@Route('post')
export class PostController extends Controller {
  @SuccessResponse('200', 'Post created')
  @Post()
  @Middlewares(validateBody(RequestClass))
  public async create(@Body() request: RequestClass): Promise<void> {
    console.log(`validated request: ${request.text}`)
  }
}

class-validator and class-transformer may need emitDecoratorMetadata depending on the decorators and transformation features you use. That requirement comes from those libraries, not from @Middlewares(...) itself.

Contributors

The avatar of contributor named as Vanna DiCatania Vanna DiCatania

Changelog

TypeScript-first OpenAPI generation, route generation, and runtime validation.