class-validator 使用教程

class-validator 使用教程

class-validatorDecorator-based property validation for classes.项目地址:https://gitcode.com/gh_mirrors/cl/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 通常与以下项目一起使用,以提供更完整的解决方案:

  1. class-transformer: 用于对象的序列化和反序列化,与 class-validator 结合使用可以实现强大的数据处理和验证。
  2. TypeORM: 一个 ORM 框架,可以与 class-validator 结合使用,实现数据库实体的自动验证。
  3. NestJS: 一个渐进式的 Node.js 框架,内置了对 class-validator 的支持,可以轻松实现模块化和可测试的应用程序。

通过这些生态项目的结合使用,class-validator 可以发挥更大的作用,提供更完整和高效的数据验证解决方案。

class-validatorDecorator-based property validation for classes.项目地址:https://gitcode.com/gh_mirrors/cl/class-validator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

娄祺杏Zebediah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值