class-validator-helper

v0.0.4 - 图1v0.0.4 - 图2
本工具主要是基于class-validatorclass-transformer做了一层简单的封装,让用户可以快速对json格式的数据进行校验,并打印出具体的参数位置。

快速入门

以下代码body没有传递address.area参数:

  1. import { Validate } from 'class-validator-helper';
  2. import {
  3. IsString,
  4. ValidateNested,
  5. IsNotEmpty,
  6. } from 'class-validator';
  7. import { Type } from 'class-transformer';
  8. class CreateUserBody$Address {
  9. @IsString()
  10. @IsNotEmpty()
  11. province: string;
  12. @IsString()
  13. @IsNotEmpty()
  14. city: string;
  15. @IsString()
  16. @IsNotEmpty()
  17. area: string;
  18. @IsString()
  19. @IsNotEmpty()
  20. detail: string;
  21. }
  22. class CreateUserBody {
  23. @IsString()
  24. @IsNotEmpty()
  25. name: string;
  26. @IsNotEmpty()
  27. @ValidateNested()
  28. @Type(() => CreateUserBody$Address)
  29. address: CreateUserBody$Address;
  30. }
  31. const body = {
  32. name: 'Reid',
  33. address: {
  34. province: '广东省',
  35. city: '广州市',
  36. detail: '开心花园'
  37. }
  38. };
  39. (async () => {
  40. await Validate(CreateUserBody, body);
  41. })();

故会报错抛出一个Error,方括号的内容为具体的参数位置,而前面是class-validator默认的提示信息,本工具会陆续取出错误信息(每次报错只会随机获取一个),直到没有错误为止:

  1. Error: area should not be empty [address.area]

函数

Validate(schema, data)

  • schema
    • 结构,传入一个class,用class-validator的装饰器进行装饰。
  • data
    • 数据,具体的json数据。

其他示例

数组提示

以下示例addresses的第二个元素没有area字段:

  1. import { Validate } from 'class-validator-helper';
  2. import {
  3. IsString,
  4. ValidateNested,
  5. IsNotEmpty,
  6. } from 'class-validator';
  7. import { Type } from 'class-transformer';
  8. class CreateUserBody$Address {
  9. @IsString()
  10. @IsNotEmpty()
  11. province: string;
  12. @IsString()
  13. @IsNotEmpty()
  14. city: string;
  15. @IsString()
  16. @IsNotEmpty()
  17. area: string;
  18. @IsString()
  19. @IsNotEmpty()
  20. detail: string;
  21. }
  22. class CreateUserBody {
  23. @IsNotEmpty()
  24. @ValidateNested({ each: true })
  25. @Type(() => CreateUserBody$Address)
  26. addresses: CreateUserBody$Address[];
  27. }
  28. const body = {
  29. addresses: [{
  30. province: '广东省',
  31. city: '广州市',
  32. area: '越秀区',
  33. detail: '开心花园'
  34. }, {
  35. province: '广东省',
  36. city: '揭阳市',
  37. detail: '开心农场'
  38. }]
  39. };
  40. (async () => {
  41. await Validate(CreateUserBody, body);
  42. })();

抛出的错误信息:

  1. Error: area should not be empty [addresses.1.area]