nestJs数据验证class-validator

一、安装

npm i --save class-validator class-transformer

class-validator 用于入的数据验证

class-transformer 用于数据格式的转换

二、使用 在main.js 开启一个全局管道 其他验证api查看 class-validator文档

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe()) //开启一个全局验证管道
  await app.listen(3000);
}
bootstrap();

在需要使用的controller中

import {IsNotEmpty} from 'class-validator'
// 这里不使用interface 原因是 interface编译成js后会被删除,同时用不了装饰器,无法在swagger显示
class CreatePostDto{ //用于对参数的限制
  @IsNotEmpty({message:'数据不为空'})//如果为空返回400
  title:string
   @IsNotEmpty({message:'数据不为空'})
  content:string
}
发布了61 篇原创文章 · 获赞 98 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/marendu/article/details/105745069