class-validator可以说是一个简化验证的依赖库 (采用注释的方式进行校验)
但是缺少中文文档和过程,以自己的理解和对官网文档的阅读进行整理输出。
它的好兄弟class-transformer
class-validator官方提供的方式还不能直接对一个请求的返回值进行校验,它要求必须要是类的一个对象,所以需要做一些处理。
可以将一个json转成指定的类的对象
import { Type, plainToClass } from 'class-transformer';
//plainToClass json转class
//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',
})
跳槽是每个人的职业生涯中都要经历的过程,不论你是搜索到的这篇文章还是无意中浏览到的这篇文章,希望你没有白白浪费停留在这里的时间,能给你接下来或者以后的笔试面试带来一些帮助。
也许是互联网未来10年中最好的一年。WINTER IS COMING。但是如果你不真正的自己去尝试尝试,你永远不知道市面上的行情如何。这次找工作下来,我自身感觉市场并没有那么可怕,也拿到了几个大厂的offer。在此进行一个总结,给自己,也希望能帮助到需要的同学。
### 面试准备
**[开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】](https://bbs.csdn.net/topics/618166371)**
面试准备根据每个人掌握的知识不同,准备的时间也不一样。现在对于前端岗位,以前也许不是很重视算法这块,但是现在很多公司也都会考。建议大家平时有空的时候多刷刷leetcode。算法的准备时间比较长,是一个长期的过程。需要在掌握了大部分前端基础知识的情况下,再有针对性的去复习算法。面试的时候算法能做出来肯定加分,但做不出来也不会一票否决,面试官也会给你提供一些思路。