Skip to content

参数校验 Validate

模块位于 src/core/Validate。在 DTO class 字段上声明规则,Controller 方法加 @Validate() 后,框架在进入业务前自动校验;失败抛 ValidationError(业务码 400)。

无需 registry

基本用法

ts
import {
  Validate,
  NotNull,
  Min,
  Max,
  Email,
  Phone,
  PostController,
  RequestBody,
} from '@/core/Application'

export class CreateUserDTO {
  @NotNull('用户名不能为空')
  @Min(2, '用户名至少 2 个字符')
  @Max(32, '用户名最多 32 个字符')
  username!: string

  @NotNull('昵称不能为空')
  nickName!: string

  @Email('邮箱格式不正确')
  email?: string

  @Phone('手机号格式不正确')
  phone?: string
}

@PostController('/create')
@Validate()
async create(@RequestBody() body: CreateUserDTO) {
  await this.userService.createUser(body)
  return null
}

注意:

  • DTO 必须是 class(不能只用 interface),否则没有运行时元数据
  • @RequestBody() 注入的是 plain object,校验按字段规则跑,不会自动 new DTO()
  • 需开启 TypeScript emitDecoratorMetadata(项目已配)

仓库示例:business/service/user.tsCreateUserDTO + user Controller 的 create

装饰器一览

装饰器说明
@Validate()方法级:开启对本方法参数的自动校验
@NotNull()拒绝 undefined / null / 空串
@Min(n)数字比大小;字符串/数组比长度;空值跳过
@Max(n)同上
@Email()邮箱格式;空值跳过
@Phone()手机号(默认 zh-CN);空值跳过
@Custom(fn, msg?)自定义函数,返回 true 通过

消息可写成字符串,或 { message: '...' }。同一字段多条规则:遇错即停

函数式校验

不通过路由装饰器时,可手动调用:

ts
import { validateHandler, notNull, email, min } from '@/core/Validate'

await validateHandler(body, CreateUserDTO)

await validateHandler(body, {
  email: [email('邮箱不对'), notNull()],
  age: [min(1)],
})

同步版:validateHandlerSync(规则内不要用 async)。

失败响应

默认由全局 Advice / 内置异常处理返回,例如:

json
{
  "code": 400,
  "message": "用户名不能为空",
  "data": [/* 字段错误明细 */]
}

详见 异常处理

相关章节

基于 VitePress 构建