【发布时间】: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 的验证应该运行
任何帮助将不胜感激
【问题讨论】: