class-validator中文教程

//type 指定隐式类型
let users = plainToClass(User, userJson);


#### 1.引入



import {
validate,
validateOrReject,
Contains,
IsInt,
Length,
IsEmail,
IsFQDN,
IsDate,
Min,
Max,
} from ‘class-validator’; //引入


#### 2.输出类



export class Post {
@Length(10, 20)
title: string;

@Contains(‘hello’)
text: string;

@IsInt()
@Min(0)
@Max(10)
rating: number;

@IsEmail()
email: string;

@IsFQDN()
site: string;

@IsDate()
createDate: Date;
} //导出类


#### 3.声明类并调用类中的方法进行校验



let post = new Post(); //声明一个post
post.title = ‘Hello’; // 不通过
post.text = ‘this is a great post about hell world’; // 不通过
post.rating = 11; // 不通过
post.email = ‘google.com’; // 不通过
post.site = ‘googlecom’; // 不通过


#### 4.验证监听



validate(post).then(errors => {
// errors is an array of validation errors
if (errors.length > 0) {
console.log('validation failed. errors: ', errors);
} else {
console.log(‘validation succeed’);
}
});


#### 5.错误输出


此方法返回一个validationError 对象 每一项如下



{
target: Object; // 已经验证的对象.
property: string; // 未通过验证的对象属性.
value: any; // 未通过验证的值.
constraints?: { // 验证失败并带有错误消息.
[type: string]: string;
};
children?: ValidationError[]; // Contains all nested validation errors of the property
}


#### 6.消息


在装饰器下提示指定信息



import { MinLength, MaxLength } from ‘class-validator’;

export class Post {
@MinLength(10, {
message: ‘Title is too short’,
})
@MaxLength(50, {
message: ‘Title is too long’,
})
title: string;
}



> 
> 在消息中可以使用特殊的$符号
> 
> 
> 



$value - 正在验证的值
$property - 要验证的对象属性的名称
$target - 要验证的对象的类的名称
$constraint1, $constraint2, … $constraintN - 由特定验证类型定义的约束


举个栗子 》》》》》》》》》



import { MinLength, MaxLength } from ‘class-validator’;

export class Post {
@MinLength(10, {
// here, $constraint1 会被替换为最小长度 “10”, $value 会被替换为换取的值
message: ‘Title is too short. Minimal length is $constraint1 characters, but actual is $value’,
})
@MaxLength(50, {
// here, $constraint1 will be replaced with “50”, and $value with actual supplied value
message: ‘Title is too long. Maximal length is $constraint1 characters, but actual is $value’,
})
title: string;
}


#### 7.检验数组的方法



import { MinLength, MaxLength } from ‘class-validator’;

export class Post {
@MaxLength(20, {
each: true, //每项验证
})
tags: string[];
}


这将验证post.tags数组中的每个项目。


#### validate函数可以选择一个validatorOptions 作为第二个参数



export interface ValidatorOptions {
skipMissingProperties?: boolean;
whitelist?: boolean;
forbidNonWhitelisted?: boolean;
groups?: string[];
dismissDefaultMessages?: boolean;
validationError?: {
target?: boolean;
value?: boolean;
};

forbidUnknownValues?: boolean; //建议设置为true 防止未知对象通过验证
stopAtFirstError?: boolean;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值