【问题标题】:How to use the class-validator conditional validation decorator (@ValidateIf) based on environment variable value如何使用基于环境变量值的类验证器条件验证装饰器(@ValidateIf)
【发布时间】:2022-01-06 02:14:28
【问题描述】:

我正在尝试使用基于环境变量值的类验证器 @ValidateIf 条件验证器装饰器。让我分享代码以更好地理解:

// .env 文件入口

AMOUNT_CHECK_IN_MODE=TEST

在我的验证器(.dto)文件中,我放置了以下代码

import {
   IsNumberString,
   Max,
   ValidateIf
} from 'class-validator';

export class GtTransactionDto {
 otherProperty: string;
 constructor() {
  this.otherProperty = process.env.AMOUNT_CHECK_IN_MODE;
}
 
 @ValidateIf(o => o.otherProperty === 'TEST')
  @Max(1, {
    message: 'Amount should not exceed 1',
    context: {
      code: GtTransactionErrorCode.validate.DestinationAmount
    },
  })
  @ValidateIf(o => o.otherProperty === 'LIVE')
  @IsNumberString(
    {},
    {
      message: 'This is not a valid $property number',
      context: {
        code: GtTransactionErrorCode.validate.DestinationAmount,
      },
    }
  )
  @ValidateIf(o => o.otherProperty === 'TEST')
  @IsNumberString(
    {},
    {
      message: 'This is not a valid $property number',
      context: {
        code: GtTransactionErrorCode.validate.DestinationAmount,
      },
    }
  )
  destinationAmount!: string; 
 }

我想确保如果 TEST 设置为 .env 文件中的 AMOUNT_CHECK_IN_MODE 的值,那么应该运行对 max amount 和 isNumberString 的验证。但是,如果该值设置为 LIVE,那么只有对 isNumberString 的验证应该运行

任何帮助将不胜感激

【问题讨论】:

    标签: node.js class-validator


    【解决方案1】:

    您可以使用Validation groups 并根据环境变量设置组。

    来自docs

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2020-09-23
      • 2013-10-31
      • 2020-04-19
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      相关资源
      最近更新 更多