class-validator 使用教程
项目介绍
class-validator
是一个基于装饰器的属性验证库,适用于类(class)。它允许开发者通过简单的装饰器来定义和执行复杂的验证规则。这个库非常适合在 TypeScript 项目中使用,可以轻松地集成到现有的项目架构中。
项目快速启动
安装
首先,你需要通过 npm 安装 class-validator
:
npm install class-validator --save
请确保使用至少 npm@6,因为从 npm@6 开始,依赖树是扁平化的,这是 class-validator
正常工作所必需的。
基本使用
创建一个类并在你想要验证的属性上添加装饰器:
import { validate, validateOrReject, Contains, IsInt, Length, IsEmail, IsFQDN, IsDate, Min, Max } from 'class-validator';
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;
}
let post = new Post();
post.title = 'Hello'; // 应该不通过
post.text = 'this is a great post about hello world'; // 应该通过
post.rating = 11; // 应该不通过
post.email = 'example@example.com'; // 应该通过
post.site = 'example.com'; // 应该通过
post.createDate = new Date(); // 应该通过
validate(post).then(errors => {
if (errors.length > 0) {
console.log('验证失败: ', errors);
} else {
console.log('验证通过');
}
});
应用案例和最佳实践
自定义验证器
你可以创建自定义验证器来满足特定的验证需求。例如,创建一个验证文本长度的自定义验证器:
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
@ValidatorConstraint({ name: 'customText', async: false })
export class CustomTextLength implements ValidatorConstraintInterface {
validate(text: string, args: ValidationArguments) {
return text.length > 1 && text.length < 10; // 异步验证需要返回一个 Promise<boolean>
}
defaultMessage(args: ValidationArguments) {
return '文本 ($value) 太短或太长';
}
}
然后在你的类中使用这个自定义验证器:
import { Validate } from 'class-validator';
import { CustomTextLength } from './CustomTextLength';
export class Post {
@Validate(CustomTextLength, {
message: '标题太短或太长'
})
title: string;
}
嵌套对象验证
class-validator
也支持嵌套对象的验证。例如:
import { ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
export class User {
@Length(10, 20)
name: string;
}
export class Post {
@ValidateNested()
@Type(() => User)
user: User;
}
典型生态项目
class-validator
通常与以下项目一起使用,以提供更完整的解决方案:
- class-transformer: 用于对象的序列化和反序列化,与
class-validator
结合使用可以实现强大的数据处理和验证。 - TypeORM: 一个 ORM 框架,可以与
class-validator
结合使用,实现数据库实体的自动验证。 - NestJS: 一个渐进式的 Node.js 框架,内置了对
class-validator
的支持,可以轻松实现模块化和可测试的应用程序。
通过这些生态项目的结合使用,class-validator
可以发挥更大的作用,提供更完整和高效的数据验证解决方案。