class-validator class-transformer nestjs的验证套路
定义一个 pipe
class testpipe implements PipeTransform{
transform(value: any, { metatype }: ArgumentMetadata){
做一些验证
不对就抛异常
对就直接返回value value会变成入参 也就是不但可以校验,还可以修改value
}
}
使用套路
@controller()
class etesxcontroller{
@post()
hello(@body(new testpipe()) dto:dto){}
//testpipe 入参value就是dto可以修改dto的value
}
class-validate 的套路
就是定义dto在dto的字段上写一些校验注解 再借助validate方法校验得到对错和消息
class dot{
id:int;
@Length(5, 10)
name:string
}
var aaa=new dot()
aaa.name="我是1"
validate(aaa).then((error)=>{
if(!error){
return true
}
console.error(error)
})
提示
[
ValidationError {
target: dot { name: '我是1' },
value: '我是1',
property: 'name',
children: [],
constraints: { isLength: 'name must be longer than or equal to 5 characters' }
}
]
transform(value: any, { metatype }: ArgumentMetadata)的参数说明
testvalite(@Body(new ValidatePipe()) dto: DTO) {
value 就是dto json metatype就是 DTO [Function]
套路 class-validator的 validate(需要一个class的实例) 所以需要class-tranform 的paintoclass 得到需要一个class的实例