class-validator 校验器的使用

6,338 阅读3分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第5天,点击查看活动详情

前言

接口请求时,为了少写成参数判断,找到一个 nest 框架中提到的一个 class-validator 校验器。在nest 框架中,通过自定义一个全局的 pipe,校验 pipe, 然后结合 class-validator 来做参数校验

post 请求中所有的 body 参数都转成 class 对象,然后在 nest 框架中,可以通过注解的方式给参数字段加上校验规则

使用方法

以 Controller body 参数的为例子,说下常用几种例子:

  • IsOptional() 选填字段校验,如果是选填的,需要再加上另外校验
  // namespace 是选填字段,如果有字段,值至少长度为1 ,
  // MinLength(1) 用于非空传递,也可以使用 IsNotEmpty()
​
  @IsOptional()
  @MinLength(1)
  namespace: string;
  • @IsArray() 是数组类型
// 是数组类型,且数组长度最小为1
  @ArrayMinSize(1)
  @IsString({each:true})
  codes: string[];
  • @IsObject 是对象类型
  • 尽量不是用 any 而是具体到各种 类型
  // 对于键值对的类型直接使用
  @IsObject()
  value : KeyValuePair // 引用的是 common/types
  • IsEnum 枚举类型
  @IsEnum(targetType)
  type: targetType;
  • IsInt 类型
  • 若是对于一些数字类型,可加上区间,不如分页最大数据量 limit 不能为负数
  @IsInt()
  @Min(1)
  limit : number
  • 其他类型
@IsBoolean()检查值是布尔型
@IsDate()检查值是日期
@IsString()检查值是字符串
@IsNumber(options: IsNumberOptions)检查值是数字
@IsInt()检查值是整数
@IsArray()检查值是数组
@IsEnum(entity: object)检查值是有效枚举
export class UsersDto {
  @IsOptional()   // 选填参数,可以加上 IsOptional 方法
  @IsString()
  @MinLength(1).  // 最小长度
  name: string;
​
  @IsNotEmpty()
  userId: string;
​
  @IsNotEmpty({ message: 'appId 不能为空' }) // 支持自定义错误信息,目前不支持显示给前端
  appId: string;
  
  @IsNotEmpty()
  @IsArry()     
  codes: string[];
  
  @IsEnum(targetTtype) // 支持枚举
  type: targetTtype;
}
​
//  controller 层的在 body 参数的使用
@Post('/api/user/update')
async updateTenant(
    @Body() update: UsersDto,
    @Req() req: IRequest,
  ) {
  // 对于默认值处理
  
}

class-validator部分校验说明

详细参考:github.com/typestack/c…

公共校验

@IsOptional()如果参数值是空的 (null 或 undefined),将忽略该字段的其他校验方法
@Equals(comparison: any)检查值是等于对比值
@NotEquals(comparison: any)检查值是不等于对比值
@IsEmpty()检查值是空的 ( '', null , undefined).
@IsNotEmpty()检查值不能为空 (!== '', !== null, !== undefined).
@IsIn(values: any[])检查值是在允许的值的数组内
@IsNotIn(values: any[])检查值是不在数组内

类型校验

@IsBoolean()检查值是布尔型
@IsDate()检查值是日期
@IsString()检查值是字符串
@IsNumber(options: IsNumberOptions)检查值是数字
@IsInt()检查值是整数
@IsArray()检查值是数组
@IsEnum(entity: object)检查值是有效枚举

数组校验

@ArrayContains(values: any[])检查数组中包含了所有的值从给定的值的数组
@ArrayNotContains(values: any[])检查数组中不包含任何给定的值。
@ArrayNotEmpty()Checks if given array is not empty.
@ArrayMinSize(min: number)Checks if the array's length is greater than or equal to the specified number.
@ArrayMaxSize(max: number)Checks if the array's length is less or equal to the specified number.
@ArrayUnique(identifier?: (o) => any)Checks if all array's values are unique. Comparison for objects is reference-based. Optional function can be speciefied which return value will be used for the comparsion.