Use class-validator+ class validator to implement form validation

preface

In the previous section, we formatted the request return using interceptors and exception filters. We also made an error response in the getOne method. In this section, we implemented form validation using a class validator + class-validator + DTO

Install dependencies

yarn add class-validator class-transformer

Use class validators

Use class validators globally

Modify the main ts class

// src/main.ts

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-execption.filter';
import { TransformInterceptor } from './interceptor/transform.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(new ValidationPipe())
  app.useGlobalInterceptors(new TransformInterceptor())
  app.useGlobalFilters(new HttpExceptionFilter())

  await app.listen(3000);
}
bootstrap();
Copy the code

Modify the exception filter to return error messages

// src/filters/http-exception.filter.ts

import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import { execPath } from 'process';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    const message = exception.message

    const exceptionResponse: any = exception.getResponse()
    let validatorMessage = exceptionResponse
    if (typeof validatorMessage === 'object') {
      validatorMessage = exceptionResponse.message[0]
    }

    response
      .status(status)
      .json({
        code: status,
        message: validatorMessage || message, }); }}Copy the code

Add a utility class to store regular expressions that you will use later

// src/utils/regex.util.ts
// a non-zero positive integer
export const regPositive: RegExp = /^[1-9]\d*$/
Copy the code

Modify article DTO

// src/modules/article/dto/list.dto.ts

import { Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";

export class ListDTO {

  @Matches(regPositive, { message: 'Page cannot be less than 0' })
  readonlypage? :number;

  @Matches(regPositive, { message: 'pageSize cannot be less than 0' })
  readonlypageSize? :number;
}
Copy the code
// src/modules/article/dto/id.dto.ts

import { IsNotEmpty, Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";

export class IdDTO {
  @Matches(regPositive, { message: 'Please enter a valid ID' })
  @IsNotEmpty({ message: 'ID cannot be null' })
  readonly id: number
Copy the code
// src/modules/article/dto/id.dto.ts

import { IsNotEmpty, Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";

export class IdDTO {
  @Matches(regPositive, { message: 'Please enter a valid ID' })
  @IsNotEmpty({ message: 'ID cannot be null' })
  readonly id: number
Copy the code
// src/modules/article/dto/article-create.dto.ts

import { IsNotEmpty } from "class-validator";

export class ArticleCreateDTO {

  @IsNotEmpty({ message: 'Please enter article title' })
  readonly title: string;

  @IsNotEmpty({ message: 'Please enter article description' })
  readonly description: string;

  @IsNotEmpty({ message: 'Please enter the content of the article' })
  readonly content: string;
}
Copy the code
// src/modules/article/dto/article-edit.dto.ts

import { IsNotEmpty, Matches } from "class-validator";
import { regPositive } from "src/utils/regex.util";
import { ArticleCreateDTO } from "./article-create.dto";

export class ArticleEditDTO extends ArticleCreateDTO {
  @Matches(regPositive, { message: 'Please enter a valid ID' })
  @IsNotEmpty({ message: 'ID cannot be null' })
  readonly id: number
}
Copy the code

At this point, we have implemented form validation for all the interfaces of Article

reference

  • NestJS
  • NestJS Chinese website
  • class-validator
  • class-transform
  • Code for this section

A series of

  • NestJS build blog system (a) – build a framework
  • NestJS build blog system (2) – write static article CURD
  • NestJS build blog system (3) – using TypeORM+Mysql to achieve data persistence
  • NestJS build blog system (three) – use interceptor, exception filter to achieve a unified return format