# @greguintow/class-validator 中文文档

规范地址：https://npmcn.com/package/%40greguintow/class-validator/

版本：0\.14\.1
npm 元数据更新时间：2023-03-01T03:32:17.627Z
中文译文更新时间：2026-11-17T00:15:54.973Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40greguintow/class-validator
原文对照：https://npmcn.com/package/%40greguintow/class-validator/?lang=original
项目主页：https://github.com/greguintow/class-validator#readme
源码仓库：https://github.com/greguintow/class-validator

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：5.1 MB，952 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2021-11-12T04:57:16.118Z
- 最新版本发布：2023-03-01T03:32:17.424Z
- 近 30 天下载量：19453（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：8（近 12 个月 0 个）

## 中文简介

以装饰为主的各类产权验证.

## 安装

```sh
npm install @greguintow/class-validator
```

也可以使用：`pnpm add @greguintow/class-validator`、`yarn add @greguintow/class-validator`、`bun add @greguintow/class-validator`

## README

# 类验证器

![Build Status](https://github.com/typestack/class-validator/workflows/CI/badge.svg) [![codecov](https://codecov.io/gh/typestack/class-validator/branch/develop/graph/badge.svg)](https://codecov.io/gh/typestack/class-validator) [![npm version](https://badge.fury.io/js/class-validator.svg)](https://badge.fury.io/js/class-validator) [![install size](https://packagephobia.now.sh/badge?p=class-validator)](https://packagephobia.now.sh/result?p=class-validator)

允许使用以装饰品和非装饰品为基础的验证. 内部用途 [验证符.js](https://github.com/chriso/validator.js) 进行验证. 类验证器在浏览器和节点.js平台上都工作.

## 目录

-   [类验证器](https://npmcn.com/package/%40greguintow/class-validator/#readme-class-validator)
    -   [目录](https://npmcn.com/package/%40greguintow/class-validator/#readme-table-of-contents)
    -   [安装](https://npmcn.com/package/%40greguintow/class-validator/#readme-installation)
    -   [使用量](https://npmcn.com/package/%40greguintow/class-validator/#readme-usage)
        -   [通过选项](https://npmcn.com/package/%40greguintow/class-validator/#readme-passing-options)
    -   [校验错误](https://npmcn.com/package/%40greguintow/class-validator/#readme-validation-errors)
    -   [验证信件](https://npmcn.com/package/%40greguintow/class-validator/#readme-validation-messages)
    -   [正在验证数组](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-arrays)
    -   [验证套件](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-sets)
    -   [验证地图](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-maps)
    -   [验证嵌入对象](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-nested-objects)
    -   [核实承诺](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-promises)
    -   [继承验证器](https://npmcn.com/package/%40greguintow/class-validator/#readme-inheriting-validation-decorators)
    -   [有条件的审定](https://npmcn.com/package/%40greguintow/class-validator/#readme-conditional-validation)
    -   [有条件 `IsOptional`](https://npmcn.com/package/%40greguintow/class-validator/#readme-conditional-isoptional)
    -   [白名单](https://npmcn.com/package/%40greguintow/class-validator/#readme-whitelisting)
    -   [将上下文传递给装饰者](https://npmcn.com/package/%40greguintow/class-validator/#readme-passing-context-to-decorators)
    -   [跳过缺失属性](https://npmcn.com/package/%40greguintow/class-validator/#readme-skipping-missing-properties)
    -   [验证组](https://npmcn.com/package/%40greguintow/class-validator/#readme-validation-groups)
    -   [自定义验证类](https://npmcn.com/package/%40greguintow/class-validator/#readme-custom-validation-classes)
    -   [自定义验证装饰器](https://npmcn.com/package/%40greguintow/class-validator/#readme-custom-validation-decorators)
    -   [使用服务容器](https://npmcn.com/package/%40greguintow/class-validator/#readme-using-service-container)
    -   [同步验证](https://npmcn.com/package/%40greguintow/class-validator/#readme-synchronous-validation)
    -   [手动验证](https://npmcn.com/package/%40greguintow/class-validator/#readme-manual-validation)
    -   [校验装饰](https://npmcn.com/package/%40greguintow/class-validator/#readme-validation-decorators)
    -   [定义没有装饰的验证方案](https://npmcn.com/package/%40greguintow/class-validator/#readme-defining-validation-schema-without-decorators)
    -   [验证普通对象](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-plain-objects)
    -   [样本](https://npmcn.com/package/%40greguintow/class-validator/#readme-samples)
    -   [扩展](https://npmcn.com/package/%40greguintow/class-validator/#readme-extensions)
    -   [发布注释](https://npmcn.com/package/%40greguintow/class-validator/#readme-release-notes)
    -   [捐款](https://npmcn.com/package/%40greguintow/class-validator/#readme-contributing)

## 安装

```sh
npm install class-validator --save
```

> 注:使用类验证器时请至少使用npm@6. 从npm@6开始,依赖树被平整,这是需要的 `class-validator` 用于正常运行.

## 使用量

创建您的类并在您想要验证的属性上设置一些验证装饰 :

```typescript
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'; // should not pass
post.text = 'this is a great post about hell world'; // should not pass
post.rating = 11; // should not pass
post.email = 'google.com'; // should not pass
post.site = 'googlecom'; // should not pass

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');
  }
});

validateOrReject(post).catch(errors => {
  console.log('Promise rejected (validation failed). Errors: ', errors);
});
// or
async function validateOrRejectExample(input) {
  try {
    await validateOrReject(input);
  } catch (errors) {
    console.log('Caught promise rejection (validation failed). Errors: ', errors);
  }
}
```

### 通过选项

这个 `validate` 函数可选择预期 a `ValidatorOptions` 作为第二个参数的对象 :

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

  forbidUnknownValues?: boolean;
  stopAtFirstError?: boolean;
}
```

> **重要性** 这个 `forbidUnknownValues` 值设定为 `true` 默认和 **高度建议保持默认值**。 。 。 . 设为 `false` 会导致未知对象通过验证!

## 校验错误

这个 `validate` 方法返回数组 `ValidationError` 对象。 每个 `ValidationError` 为:

```typescript
{
    target: Object; // Object that was validated.
    property: string; // Object's property that haven't pass validation.
    value: any; // Value that haven't pass a validation.
    constraints?: { // Constraints that failed validation with error messages.
        [type: string]: string;
    };
    children?: ValidationError[]; // Contains all nested validation errors of the property
}
```

在我们的情况中,当我们验证一个邮局对象时,我们有这样一系列 `ValidationError` 对象 :

```typescript
[{
    target: /* post object */,
    property: "title",
    value: "Hello",
    constraints: {
        length: "$property must be longer than or equal to 10 characters"
    }
}, {
    target: /* post object */,
    property: "text",
    value: "this is a great post about hell world",
    constraints: {
        contains: "text must contain a hello string"
    }
},
// and other errors
]
```

如果你不想要一个 `target` 要在验证错误中被曝光, 当您使用验证符时有一个特殊选项 :

```typescript
validator.validate(post, { validationError: { target: false } });
```

当你在 http 上发出错误时,这特别有用, 你很可能不想曝光 整个目标对象.

## 验证信件

您可以在装饰器选项中指定校验信件, 信件将在 `ValidationError` 返回时间 `validate` 方法(如果此字段的验证失败).

```typescript
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` - 具体审定类型的限制

使用实例:

```typescript
import { MinLength, MaxLength } from 'class-validator';

export class Post {
  @MinLength(10, {
    // here, $constraint1 will be replaced with "10", and $value with actual supplied 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;
}
```

您也可以提供函数, 返回消息 。 这允许您创建更多颗粒式消息 :

```typescript
import { MinLength, MaxLength, ValidationArguments } from 'class-validator';

export class Post {
  @MinLength(10, {
    message: (args: ValidationArguments) => {
      if (args.value.length === 1) {
        return 'Too short, minimum length is 1 character';
      } else {
        return 'Too short, minimum length is ' + args.constraints[0] + ' characters';
      }
    },
  })
  title: string;
}
```

接受信件函数 `ValidationArguments` 其中载有下列资料:

-   `value` - 正在验证的值
-   `constraints` - 具体审定类型的限制范围
-   `targetName` - 正在验证对象类别的名称
-   `object` - 正在验证的对象
-   `property` - 正在验证对象财产的名称

## 正在验证数组

如果您的字段是数组, 您想要对数组中的每个项目进行校验, 您必须指定一个 特别 `each: true` 装饰选项 :

```typescript
import { MinLength, MaxLength } from 'class-validator';

export class Post {
  @MaxLength(20, {
    each: true,
  })
  tags: string[];
}
```

这将验证每个项目在 `post.tags` 阵列.

## 验证套件

如果您的字段是一组, 您想要对一组中的每个项目进行校验, 您必须指定一个 特别 `each: true` 装饰选项 :

```typescript
import { MinLength, MaxLength } from 'class-validator';

export class Post {
  @MaxLength(20, {
    each: true,
  })
  tags: Set<string>;
}
```

这将验证每个项目在 `post.tags` 设置.

## 验证地图

如果您的字段是地图, 您想要对地图中的每个项目进行校验, 您必须指定一个 特别 `each: true` 装饰选项 :

```typescript
import { MinLength, MaxLength } from 'class-validator';

export class Post {
  @MaxLength(20, {
    each: true,
  })
  tags: Map<string, string>;
}
```

这将验证每个项目在 `post.tags` 地图.

## 验证嵌入对象

如果您的对象包含嵌入对象, 您希望验证器也能进行验证, 那么您需要 使用该 `@ValidateNested()` 装饰 :

```typescript
import { ValidateNested } from 'class-validator';

export class Post {
  @ValidateNested()
  user: User;
}
```

请注意嵌入对象 _必须_ 成为阶级的例子,否则 `@ValidateNested` 不知道什么等级是验证的目标。 检查 [验证普通对象](https://npmcn.com/package/%40greguintow/class-validator/#readme-validating-plain-objects)。 。 。 .

它还与多维阵列合作,例如:

```typescript
import { ValidateNested } from 'class-validator';

export class Plan2D {
  @ValidateNested()
  matrix: Point[][];
}
```

## 核实承诺

如果对象包含属性 `Promise`\- 应验证的返回值,然后需要使用 `@ValidatePromise()` 装饰 :

```typescript
import { ValidatePromise, Min } from 'class-validator';

export class Post {
  @Min(0)
  @ValidatePromise()
  userId: Promise<number>;
}
```

也和我们一起工作 `@ValidateNested` 装饰 :

```typescript
import { ValidateNested, ValidatePromise } from 'class-validator';

export class Post {
  @ValidateNested()
  @ValidatePromise()
  user: Promise<User>;
}
```

## 继承验证器

当定义从另一类延伸的子类时,子类会自动继承父的装饰. 如果在后人中重新定义一个地产,则会从自己的地级和地级上对地产进行分类装饰.

```typescript
import { validate } from 'class-validator';

class BaseContent {
  @IsEmail()
  email: string;

  @IsString()
  password: string;
}

class User extends BaseContent {
  @MinLength(10)
  @MaxLength(20)
  name: string;

  @Contains('hello')
  welcome: string;

  @MinLength(20)
  password: string;
}

let user = new User();

user.email = 'invalid email'; // inherited property
user.password = 'too short'; // password wil be validated not only against IsString, but against MinLength as well
user.name = 'not valid';
user.welcome = 'helo';

validate(user).then(errors => {
  // ...
}); // it will return errors for email, title and text properties
```

## 有条件的审定

有条件的校验装饰( E)`@ValidateIf`当提供的条件函数返回虚假时,可以用于忽略属性上的验证符. 条件函数需要验证对象,必须返回一个 `boolean`。 。 。 .

```typescript
import { ValidateIf, IsNotEmpty } from 'class-validator';

export class Post {
  otherProperty: string;

  @ValidateIf(o => o.otherProperty === 'value')
  @IsNotEmpty()
  example: string;
}
```

在上述例子中,审定规则适用于: `example` 除非对象是 `otherProperty` 实值 `"value"`。 。 。 .

请注意,当条件不实时,所有验证装饰都被忽视,包括: `isDefined`。 。 。 .

## 有条件 `IsOptional`

同样的过程,装饰者 `IsOptional` 接受允许删除条件函数 `IsOptional` 当返回假.

```typescript
import { IsOptional } from 'class-validator';

export class Place {
  @IsOptional(o => o.latitude === undefined)
  @IsNotEmpty()
  @IsNumber()
  longitude: number;

  @IsOptional(o => o.longitude === undefined)
  @IsNotEmpty()
  @IsNumber()
  latitude: number;
}
```

## 白名单

即使您的对象是一个验证类的例子, 它也可以包含未定义的额外属性 . 如果您不想在对象上有这样的属性,请通过特殊旗帜 `validate` 方法 :

```typescript
import { validate } from 'class-validator';
// ...
validate(post, { whitelist: true });
```

这将剥去所有没有装饰器的属性. 如果没有其他装饰家适合你的财产, 您可以使用 @ Allow 装饰器 :

```typescript
import {validate, Allow, Min} from "class-validator";

export class Post {

    @Allow()
    title: string;

    @Min(0)
    views: number;

    nonWhitelistedProperty: number;
}

let post = new Post();
post.title = 'Hello world!';
post.views = 420;

post.nonWhitelistedProperty = 69;
(post as any).anotherNonWhitelistedProperty = "something";

validate(post).then(errors => {
  // post.nonWhitelistedProperty is not defined
  // (post as any).anotherNonWhitelistedProperty is not defined
  ...
});
```

如果您更愿意在存在任何非白名单属性时出现出错, 请另传一面旗帜到 `validate` 方法 :

```typescript
import { validate } from 'class-validator';
// ...
validate(post, { whitelist: true, forbidNonWhitelisted: true });
```

## 将上下文传递给装饰者

可以将一个自定义对象传递给装饰者,在 `ValidationError` 实例,如果验证失败.

```ts
import { validate } from 'class-validator';

class MyClass {
  @MinLength(32, {
    message: 'EIC code must be at least 32 characters',
    context: {
      errorCode: 1003,
      developerNote: 'The validated string must contain 32 or more characters.',
    },
  })
  eicCode: string;
}

const model = new MyClass();

validate(model).then(errors => {
  //errors[0].contexts['minLength'].errorCode === 1003
});
```

## 跳过缺失属性

有时,您可能想要跳过验证对象中不存在的属性。 这是 通常在想要更新对象的某些部分时可取,并且只想要验证更新的部分, 但跳过其他一切,例如跳过缺失属性. 在这种情况下,你需要通过特殊旗帜 `validate` 方法 :

```typescript
import { validate } from 'class-validator';
// ...
validate(post, { skipMissingProperties: true });
```

当跳过缺失属性时,有时你不想跳过所有缺失属性,有些属性可能需要 对于你,即使跳过 MissingProperties 被设定为真实。 对于这种情况,您应当使用 `@IsDefined()` 装饰师. `@IsDefined()` 是唯一忽略 `skipMissingProperties` 选项.

## 验证组

在不同情况下,您可能想要使用同一对象的不同验证方案. 在这种情况下,您可以使用验证组.

> **重要性** 调用组组合的校验, 但不会导致校验( 如: 不存在组名) 将会导致未知的值出错。 在与组进行校验时,所提供的组组合应至少匹配一个装饰器.

```typescript
import { validate, Min, Length } from 'class-validator';

export class User {
  @Min(12, {
    groups: ['registration'],
  })
  age: number;

  @Length(2, 20, {
    groups: ['registration', 'admin'],
  })
  name: string;
}

let user = new User();
user.age = 10;
user.name = 'Alex';

validate(user, {
  groups: ['registration'],
}); // this will not pass validation

validate(user, {
  groups: ['admin'],
}); // this will pass validation

validate(user, {
  groups: ['registration', 'admin'],
}); // this will not pass validation

validate(user, {
  groups: undefined, // the default
}); // this will not pass validation since all properties get validated regardless of their groups

validate(user, {
  groups: [],
}); // this will not pass validation, (equivalent to 'groups: undefined', see above)
```

还有一面特别的旗帜 `always: true` 用于验证选项。 这旗子上写着这次验证 无论使用哪个组,必须始终适用.

## 自定义验证类

如果您有自定义验证逻辑, 您可以创建 _约束类_数字 :

1.  首先创建一个文件, 可以说 `CustomTextLength.ts`,并定义新类:
    
    ```typescript
    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; // for async validations you must return a Promise<boolean> here
      }
    
      defaultMessage(args: ValidationArguments) {
        // here you can provide default error message if validation failed
        return 'Text ($value) is too short or too long!';
      }
    }
    ```
    
    我们的班级标志 `@ValidatorConstraint` 装饰师. 您也可以提供验证约束名称 - 此名称将在验证 Error 中用作" error type" . 如果您不会提供约束名称 - 它会自动生成 .
    
    我们的阶级必须执行 `ValidatorConstraintInterface` 接口及其 `validate` 方法, 定义验证逻辑。 如果验证成功,方法返回真实,否则是虚假的. 自定义验证器可以是同步的, 如果您想要在同步后执行验证 操作,只需返回一个承诺 里面布尔 `validate` 方法.
    
    我们还定义了可选方法 `defaultMessage` 定义默认错误消息, 如果装饰者的执行没有设置错误信息.
    
2.  然后,你可以在你的班级里使用新的验证限制:
    
    ```typescript
    import { Validate } from 'class-validator';
    import { CustomTextLength } from './CustomTextLength';
    
    export class Post {
      @Validate(CustomTextLength, {
        message: 'Title is too short or long!',
      })
      title: string;
    }
    ```
    
    在这里,我们设置 我们的新创造 `CustomTextLength` 验证限制 `Post.title`。 。 。 .
    
3.  按惯例使用验证符 :
    
    ```typescript
    import { validate } from 'class-validator';
    
    validate(post).then(errors => {
      // ...
    });
    ```
    

您也可以将限制传递给您的验证人, 像这样:

```typescript
import { Validate } from 'class-validator';
import { CustomTextLength } from './CustomTextLength';

export class Post {
  @Validate(CustomTextLength, [3, 20], {
    message: 'Wrong post title',
  })
  title: string;
}
```

用他们从 `validationArguments` 对象 :

```typescript
import { ValidationArguments, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';

@ValidatorConstraint()
export class CustomTextLength implements ValidatorConstraintInterface {
  validate(text: string, validationArguments: ValidationArguments) {
    return text.length > validationArguments.constraints[0] && text.length < validationArguments.constraints[1];
  }
}
```

## 自定义验证装饰器

您也可以创建自定义装饰器 。 它是使用自定义验证最优雅的方式. 让我们创建一个名为 `@IsLongerThan`数字 :

1.  创建装饰器 :
    
    ```typescript
    import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';
    
    export function IsLongerThan(property: string, validationOptions?: ValidationOptions) {
      return function (object: Object, propertyName: string) {
        registerDecorator({
          name: 'isLongerThan',
          target: object.constructor,
          propertyName: propertyName,
          constraints: [property],
          options: validationOptions,
          validator: {
            validate(value: any, args: ValidationArguments) {
              const [relatedPropertyName] = args.constraints;
              const relatedValue = (args.object as any)[relatedPropertyName];
              return typeof value === 'string' && typeof relatedValue === 'string' && value.length > relatedValue.length; // you can return a Promise<boolean> here as well, if you want to make async validation
            },
          },
        });
      };
    }
    ```
    
2.  将其用于:
    
    ```typescript
    import { IsLongerThan } from './IsLongerThan';
    
    export class Post {
      title: string;
    
      @IsLongerThan('title', {
        /* you can also use additional validation options, like "groups" in your custom validation decorators. "each" is not supported */
        message: 'Text must be longer than the title',
      })
      text: string;
    }
    ```
    

在您的自定义装饰器中, 您也可以使用 `ValidationConstraint`。 。 。 . 让我们创建另一个名为自定义验证的装饰器 `IsUserAlreadyExist`数字 :

1.  创建验证约束和装饰 :
    
    ```typescript
    import {
      registerDecorator,
      ValidationOptions,
      ValidatorConstraint,
      ValidatorConstraintInterface,
      ValidationArguments,
    } from 'class-validator';
    
    @ValidatorConstraint({ async: true })
    export class IsUserAlreadyExistConstraint implements ValidatorConstraintInterface {
      validate(userName: any, args: ValidationArguments) {
        return UserRepository.findOneByName(userName).then(user => {
          if (user) return false;
          return true;
        });
      }
    }
    
    export function IsUserAlreadyExist(validationOptions?: ValidationOptions) {
      return function (object: Object, propertyName: string) {
        registerDecorator({
          target: object.constructor,
          propertyName: propertyName,
          options: validationOptions,
          constraints: [],
          validator: IsUserAlreadyExistConstraint,
        });
      };
    }
    ```
    
    我们指出,我们的制约因素是,它将通过增加: `{ async: true }` 在验证选项中.
    
2.  并把它用于:
    
    ```typescript
    import { IsUserAlreadyExist } from './IsUserAlreadyExist';
    
    export class User {
      @IsUserAlreadyExist({
        message: 'User $value already exists. Choose another name.',
      })
      name: string;
    }
    ```
    

## 使用服务容器

如果想要在您的自定义验证器约束中注入依赖性, 验证器会支持服务容器 课程。 以下是如何将其与 [类型di](https://github.com/pleerock/typedi)数字 :

```typescript
import { Container } from 'typedi';
import { useContainer, Validator } from 'class-validator';

// do this somewhere in the global application level:
useContainer(Container);
let validator = Container.get(Validator);

// now everywhere you can inject Validator class which will go from the container
// also you can inject classes using constructor injection into your custom ValidatorConstraint-s
```

## 同步验证

如果您想要进行简单的非同步验证, 您可以使用 `validateSync` 方法而不是常规 `validate` 方法。 其论据与 `validate` 方法。 注意,这个方法 **忽略** 全部同步验证 没错.

## 手动验证

验证器中有几种方法允许进行基于非装饰的验证:

```typescript
import { isEmpty, isBoolean } from 'class-validator';

isEmpty(value);
isBoolean(value);
```

## 校验装饰

| 装饰 | 说明 |
| --- | --- |
| **通用验证装饰器** |  |
| `@IsDefined(value: any)` | 检查是否定义了值(!=================== 这是唯一一个忽略“Properties”选项的装饰器. |
| `@IsOptional(condition?: function)` | 检查给定的值是否为空 (QQ 无效, QQ 未定义) 如果为空, 请忽略属性上的所有验证符 . |
| `@Equals(comparison: any)` | 检查值是否等于(" ")比较. |
| `@NotEquals(comparison: any)` | 请检查archive-date=中的日期值 (帮助). |
| `@IsEmpty()` | 检查给定值是否为空( QQ '', QQ 无效, QQ 未定义) . |
| `@IsNotEmpty()` | 检查给定值是否为空 (! =='''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''未''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''. |
| `@IsIn(values: any[])` | 检查值是否在允许的值阵列中 . |
| `@IsNotIn(values: any[])` | 检查数值是否在一系列不允许的数值中 . |
| **类型验证装饰器** |  |
| `@IsBoolean()` | 检查一个值是否是布尔值 . |
| `@IsDate()` | 检查该值是否为日期 . |
| `@IsString()` | 检查该值是否为字符串. |
| `@IsNumber(options: IsNumberOptions)` | 检查值是否是一个数字. |
| `@IsInt()` | 检查数值是否为整数. |
| `@IsArray()` | 检查该值是否是一个数组 |
| `@IsEnum(entity: object)` | 检查该值是否为有效的 enum |
| **数量 校验装饰** |  |
| `@IsDivisibleBy(num: number)` | 检查该值是否是另一个可分辨的数字 . |
| `@IsPositive()` | 检查数值是否是一个大于0的正数 . |
| `@IsNegative()` | 检查数值是否是一个小于零的负数 . |
| `@Min(min: number)` | 检查给定数字是否大于或等于给定数字. |
| `@Max(max: number)` | 检查给定的数字是否小于或等于给定的数字. |
| **日期验证装饰** |  |
| `@MinDate(date: Date | (() => Date))` | 检查该值是否是指定日期后的日期 . |
| `@MaxDate(date: Date | (() => Date))` | 检查该值是否是指定日期之前的日期 . |
| **字符串类型验证装饰器** |  |
| `@IsBooleanString()` | 检查字符串是否为布尔(例如"真"或"假"或"1","0"). |
| `@IsDateString()` | 别名 `@IsISO8601()`。 。 。 . |
| `@IsNumberString(options?: IsNumericOptions)` | 检查字符串是否是一个数字. |
| **字符串验证装饰器** |  |
| `@Contains(seed: string)` | 检查字符串是否包含种子 . |
| `@NotContains(seed: string)` | 检查字符串是否包含种子 . |
| `@IsAlpha()` | 检查字符串是否只包含字母(a-zA-Z). |
| `@IsAlphanumeric()` | 检查字符串是否只包含字母和数字 . |
| `@IsDecimal(options?: IsDecimalOptions)` | 检查字符串是否是一个有效的小数值。 默认异构选项是 `force_decimal=False`, (中文(简体) ), `decimal_digits: '1,'`, (中文(简体) ), `locale: 'en-US'` |
| `@IsAscii()` | 检查字符串是否只包含 ASCII 字符 . |
| `@IsBase32()` | 检查字符串是否为基数32编码 . |
| `@IsBase58()` | 检查字符串是否被编码为 Base58 . |
| `@IsBase64(options?: IsBase64Options)` | 检查一个字符串是否被编码为 Base64 . |
| `@IsIBAN()` | 检查字符串是否为 IBAN( 国际银行帐户编号) . |
| `@IsBIC()` | 检查字符串是BIC(银行识别码)还是SWIFT代码. |
| `@IsByteLength(min: number, max?: number)` | 检查字符串的长度( 以字节计) 是否在一定范围内 . |
| `@IsCreditCard()` | 检查字符串是否是信用卡 . |
| `@IsCurrency(options?: IsCurrencyOptions)` | 检查字符串是否为有效货币金额 . |
| `@IsISO4217CurrencyCode()` | 检查字符串是否为ISO 4217货币代码. |
| `@IsEthereumAddress()` | 使用基本 regex 检查字符串是否为 Ethereum 地址 。 不验证地址校验和 . |
| `@IsBtcAddress()` | 检查字符串是否是一个有效的 BTC 地址 . |
| `@IsDataURI()` | 检查字符串是否为数据uri格式. |
| `@IsEmail(options?: IsEmailOptions)` | 检查字符串是否为电子邮件 . |
| `@IsFQDN(options?: IsFQDNOptions)` | 检查字符串是否是一个完全合格的域名(如域名.com). |
| `@IsFullWidth()` | 检查字符串中是否有全宽字符 . |
| `@IsHalfWidth()` | 检查字符串是否包含有半宽字符 . |
| `@IsVariableWidth()` | 检查字符串是否包含全和半宽字符的混合物 . |
| `@IsHexColor()` | 检查字符串是否为十六进制颜色 . |
| `@IsHSL()` | 检查字符串是否基于 HSL 颜色 [CSS 第4级颜色规格](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value)。 。 。 . |
| `@IsRgbColor(options?: IsRgbOptions)` | 检查字符串是否为 rgb 或 rgba 颜色 . |
| `@IsIdentityCard(locale?: string)` | 检查字符串是否为有效身份证代码. |
| `@IsPassportNumber(countryCode?: string)` | 检查字符串相对于特定国家代码是否是一个有效的护照号码. |
| `@IsPostalCode(locale?: string)` | 检查字符串是否为邮政编码 . |
| `@IsHexadecimal()` | 检查字符串是否为十六进制数 . |
| `@IsOctal()` | 检查字符串是否为八进制数字 . |
| `@IsMACAddress(options?: IsMACAddressOptions)` | 检查字符串是否为 MAC 地址 . |
| `@IsIP(version?: "4"|"6")` | 检查字符串是否为 IP (版本 4 或 6) . |
| `@IsPort()` | 检查字符串是否是一个有效的端口号码. |
| `@IsISBN(version?: "10"|"13")` | 检查字符串是否为 ISBN( 第10版或 第13版) . |
| `@IsEAN()` | 检查字符串是否为 EAN (欧洲文章编号) . |
| `@IsISIN()` | 检查字符串是否为 ISIN( 库存/ 安全标识符) . |
| `@IsISO8601(options?: IsISO8601Options)` | 检查字符串是否为有效的ISO 8601日期格式. 严格使用选项=对有效日期的额外检查为真. |
| `@IsJSON()` | 检查字符串是否有效 . |
| `@IsJWT()` | 检查字符串是否有效的 JWT . |
| `@IsObject()` | 检查对象是否是有效的对象(无效,函数,阵列会返回假). |
| `@IsNotEmptyObject()` | 检查对象是否为空 . |
| `@IsLowercase()` | 检查字符串是否为小写 . |
| `@IsLatLong()` | 检查字符串是否为格式lat,长度中有效的经纬坐标. |
| `@IsLatitude()` | 检查字符串或数字是否为有效的纬度坐标 . |
| `@IsLongitude()` | 检查字符串或数字是否是一个有效的经度坐标. |
| `@IsMobilePhone(locale: string)` | 检查字符串是否为手机号码 . |
| `@IsISO31661Alpha2()` | 检查字符串是否为有效的ISO 3166-1 alpha-2正式指定的国家代码. |
| `@IsISO31661Alpha3()` | 检查字符串是否为有效的ISO 3166-1 alpha-3正式指定的国家代码. |
| `@IsLocale()` | 检查字符串是否为本地语言 . |
| `@IsPhoneNumber(region: string)` | 检查字符串是否是使用 libphone number-js 的有效电话号码 . |
| `@IsMongoId()` | 检查字符串是否是MongoDB ObjectId 的有效六进制代表 . |
| `@IsMultibyte()` | 检查字符串是否包含一个或多个多字节字符 . |
| `@IsNumberString(options?: IsNumericOptions)` | 检查字符串是否为数字 . |
| `@IsSurrogatePair()` | 检查字符串是否包含任何代对字符 . |
| `@IsTaxId()` | 检查字符串是否为有效的税务ID 。 默认地址是 `en-US`。 。 。 . |
| `@IsUrl(options?: IsURLOptions)` | 检查字符串是否为 URL . |
| `@IsMagnetURI()` | 检查字符串是否为 [磁铁uri格式](https://en.wikipedia.org/wiki/Magnet_URI_scheme)。 。 。 . |
| `@IsUUID(version?: UUIDVersion)` | 检查字符串是否为 UUID( 第 3, 4, 5 版或全部 ) . |
| `@IsFirebasePushId()` | 检查字符串是否为 [火力基地 推取ID](https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html) |
| `@IsUppercase()` | 检查字符串是否为大写 . |
| `@Length(min: number, max?: number)` | 检查字符串的长度是否在一定范围内下降. |
| `@MinLength(min: number)` | 检查字符串长度是否不小于给定的数字 . |
| `@MaxLength(max: number)` | 检查字符串的长度是否大于给定的数字 . |
| `@Matches(pattern: RegExp, modifiers?: string)` | 检查字符串是否符合模式 。 或匹配("foo",/foo/i)或匹配("foo","foo","i"). |
| `@IsMilitaryTime()` | 检查字符串是否以HH:MM格式有效表示军事时间. |
| `@IsTimeZone()` | 检查字符串是否代表有效的 IANA 时区 . |
| `@IsHash(algorithm: string)` | 检查字符串是否为散列 支持下列类型:`md4`, (中文(简体) ), `md5`, (中文(简体) ), `sha1`, (中文(简体) ), `sha256`, (中文(简体) ), `sha384`, (中文(简体) ), `sha512`, (中文(简体) ), `ripemd128`, (中文(简体) ), `ripemd160`, (中文(简体) ), `tiger128`, (中文(简体) ), `tiger160`, (中文(简体) ), `tiger192`, (中文(简体) ), `crc32`, (中文(简体) ), `crc32b`。 。 。 . |
| `@IsMimeType()` | 检查字符串是否匹配到一个有效的 [MIME 类型](https://en.wikipedia.org/wiki/Media_type) 格式 |
| `@IsSemVer()` | 检查字符串是否为语义版规格(SemVer). |
| `@IsISSN(options?: IsISSNOptions)` | 检查字符串是否为 ISSN . |
| `@IsISRC()` | 检查字符串是否为 [伊斯兰救济会](https://en.wikipedia.org/wiki/International_Standard_Recording_Code)。 。 。 . |
| `@IsRFC3339()` | 检查字符串是否有效 [RFC 3339 (法语)](https://tools.ietf.org/html/rfc3339) 约会. |
| `@IsStrongPassword(options?: IsStrongPasswordOptions)` | 检查字符串是否是一个强烈的密码 . |
| **阵列校正器** |  |
| `@ArrayContains(values: any[])` | 检查数组是否包含来自给定数组的所有值 . |
| `@ArrayNotContains(values: any[])` | 检查数组是否不包含任何给定值 . |
| `@ArrayNotEmpty()` | 检查给定数组是否不是空的 . |
| `@ArrayMinSize(min: number)` | 检查数组长度是否大于或等于指定的数字. |
| `@ArrayMaxSize(max: number)` | 检查数组的长度是否小于或等于指定的数字. |
| `@ArrayUnique(identifier?: (o) => any)` | 检查所有阵列的值是否是独一无二的 。 对对象的比较基于参考。 可选函数可以被定型,返回值将被用于比较. |
| **对象验证装饰器** |  |
| `@IsInstance(value: any)` | 检查属性是否为过值实例 . |
| **其他装饰** |  |
| `@Allow()` | 防止在没有规定其他限制的情况下剥离财产. |
| `@ForbidIf(condition: function)` | 如果条件匹配, 禁止插入属性 |

## 定义没有装饰的验证方案

没有装饰器的基于 Schema 的验证不再由 `class-validator`。这个功能在0.12版本被打破,不会被固定。 如果您对基于计划的验证感兴趣, 您可以在其中找到多个这样的框架 [佐德读取的比较部分](https://github.com/colinhacks/zod#comparison)。 。 。 .

## 验证普通对象

由于装饰者的性质,验证对象必须使用即时 `new Class()` 语法. 如果您使用类校正器定义了您的类, 您想要验证普通 JS 对象( 文学对象或 JSON. parse 返回) , 您需要通过使用将其转换为类实例 [类转换器](https://github.com/pleerock/class-transformer)) (中文(简体) ).

## 样本

看看里面的样本 [./样本](https://github.com/pleerock/class-validator/tree/master/sample) 更多实例 诸用相.

## 扩展

有几个扩展简化类验证器与其他模块的集成:

-   [类验证器集成](https://github.com/19majkel94/class-transformer-validator) 与 [类转换器](https://github.com/pleerock/class-transformer)
-   [类验证规则](https://github.com/yantrab/class-validator-rule)
-   [ngx-动力-形式-构建器](https://github.com/EndyKaufman/ngx-dynamic-form-builder)
-   [abarghoud/ngx反应-形式-级验证器](https://github.com/abarghoud/ngx-reactive-form-class-validator)

## 发布注释

参见关于突破更改和发布注释的信息 [这里](https://npmcn.com/package/%40greguintow/class-validator/CHANGELOG.md)。 。 。 .

## 捐款

关于如何为该项目作出贡献的信息,参见: [TypeStack 的一般贡献指南](https://github.com/typestack/.github/blob/master/CONTRIBUTING.md)。 。 。 .

## 常见问题

### @greguintow/class-validator 是什么？

以装饰为主的各类产权验证\.

### 如何安装 @greguintow/class-validator？

在项目目录运行 npm install @greguintow/class-validator，或使用 pnpm add / yarn add / bun add。

### @greguintow/class-validator 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @greguintow/class-validator 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @greguintow/class-validator 可以商用吗？

@greguintow/class-validator 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @greguintow/class-validator 的下载量有多少？

根据 npm 官方下载统计，@greguintow/class-validator 在 2026/10/17 – 2026/11/15 这 30 天内被下载 19,453 次，日均约 648 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @greguintow/class-validator 还在维护吗？

最新版本 0\.14\.1 发布于 2023/03/01（3 年前）；至今共发布 8 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/11/12。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

