相关包下载
pnpm install class-validator class-transformer
全局使用
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from "@nestjs/common";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 全局使用管道,用于 Controller 层参数校验
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
用法说明
// class-validator 常用的装饰器:
// @IsNumber():验证值是否为数字类型
// @IsString():验证值是否为字符串类型
// @IsBoolean():验证值是否为布尔类型
// @IsNotEmpty():验证值是否非空
// @IsOptional():验证值是否可选
// @IsEmail():验证值是否为有效的电子邮件地址
// @IsUrl():验证值是否为有效的 URL 地址
// @IsDate():验证值是否为有效的日期
// @Min():验证值是否大于或等于指定的最小值
// @Max():验证值是否小于或等于指定的最大值
// @Length():验证字符串长度是否在指定的范围内
// @Matches():验证字符串是否匹配指定的正则表达式
// @IsIn():验证值是否属于指定的允许值列表
// @IsNotEmptyObject():验证对象是否为非空对象
例如:
import { IsNotEmpty, IsString, IsNumber, IsIn } from "class-validator";
export class AddUserDto {
@IsNotEmpty({ message: "id should not be empty" })
@IsNumber({ allowNaN: false }, { message: "id must be a number" })
id: number;
@IsNotEmpty()
@IsString()
name: string;
@IsNotEmpty()
@IsNumber()
age: number;
@IsNotEmpty()
@IsIn([1, 2])
gender: string;
}
参数校验在控制层起作用,如在user.controller.ts
中:
addUser(@Body() userData: AddUserDto): UserItem[] {
return this.userService.addUser(userData);
}
参考文章:参数校验 | Nest.js 入门及实践 (yingjieweb.github.io)
版本
- nodejs:20.9.0
- npm:10.1.0
- nestjs:10.0.0