class-validator 使用教程
2026-01-17 08:38:11作者:郁楠烈Hubert
项目介绍
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 可以发挥更大的作用,提供更完整和高效的数据验证解决方案。
登录后查看全文
热门项目推荐
相关项目推荐
kernelopenEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。C0111
baihu-dataset异构数据集“白虎”正式开源——首批开放10w+条真实机器人动作数据,构建具身智能标准化训练基座。00
mindquantumMindQuantum is a general software library supporting the development of applications for quantum computation.Python059
PaddleOCR-VLPaddleOCR-VL 是一款顶尖且资源高效的文档解析专用模型。其核心组件为 PaddleOCR-VL-0.9B,这是一款精简却功能强大的视觉语言模型(VLM)。该模型融合了 NaViT 风格的动态分辨率视觉编码器与 ERNIE-4.5-0.3B 语言模型,可实现精准的元素识别。Python00
GLM-4.7GLM-4.7上线并开源。新版本面向Coding场景强化了编码能力、长程任务规划与工具协同,并在多项主流公开基准测试中取得开源模型中的领先表现。 目前,GLM-4.7已通过BigModel.cn提供API,并在z.ai全栈开发模式中上线Skills模块,支持多模态任务的统一规划与协作。Jinja00
AgentCPM-Explore没有万亿参数的算力堆砌,没有百万级数据的暴力灌入,清华大学自然语言处理实验室、中国人民大学、面壁智能与 OpenBMB 开源社区联合研发的 AgentCPM-Explore 智能体模型基于仅 4B 参数的模型,在深度探索类任务上取得同尺寸模型 SOTA、越级赶上甚至超越 8B 级 SOTA 模型、比肩部分 30B 级以上和闭源大模型的效果,真正让大模型的长程任务处理能力有望部署于端侧。Jinja00
项目优选
收起
deepin linux kernel
C
27
11
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
485
3.59 K
Ascend Extension for PyTorch
Python
297
329
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
260
111
暂无简介
Dart
735
177
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
65
20
Nop Platform 2.0是基于可逆计算理论实现的采用面向语言编程范式的新一代低代码开发平台,包含基于全新原理从零开始研发的GraphQL引擎、ORM引擎、工作流引擎、报表引擎、规则引擎、批处理引引擎等完整设计。nop-entropy是它的后端部分,采用java语言实现,可选择集成Spring框架或者Quarkus框架。中小企业可以免费商用
Java
11
1
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
861
456
React Native鸿蒙化仓库
JavaScript
294
343
仓颉编译器源码及 cjdb 调试工具。
C++
148
880