我的NestJS控制器中有以下DTO对象作为请求主体的一部分:
export class UserPropertiesDto {
[key: string]: boolean;
}
例如:{campaignActive: true, metadataEnabled: false}
它是一个键值对object
,其中键是唯一的string
,其值是boolean
。
我想应用class-validator
注释来确保正确的验证和转换,但它一直显示错误Decorators are not valid here
:
export class UserPropertiesDto {
@IsOptional()
@IsString() // `key` should be a string
@MaxLength(20) // `key` should have no more than 20 characters
@IsBoolean() // `value` has to be a `boolean`
[key: string]: boolean;
}
你能就最好的方法提出建议吗:
- 确保保留所有对象的属性
- 验证密钥以确保其长度不超过20个字符
- 验证值以确保它是
boolean
我建议您使用自定义验证器,我尝试为您做一些工作:
iskeyvalue验证器.ts
import { ValidatorConstraint, ValidatorConstraintInterface,
ValidationArguments }
from
"class-validator";
import { Injectable } from '@nestjs/common';
@Injectable()
@ValidatorConstraint({ async: true })
export class IsKeyValueValidate implements ValidatorConstraintInterface {
async validate(colmunValue: Object, args: ValidationArguments) {
try {
if(this.isObject(colmunValue))
return false;
var isValidate = true;
Object.keys(colmunValue)
.forEach(function eachKey(key) {
if(key.length > 20 || typeof key != "string" || typeof colmunValue[key] !=
"boolean")
{
isValidate = false;
}
});
return isValidate ;
} catch (error) {
console.log(error);
}
}
isObject(objValue) {
return objValue && typeof objValue === 'object' && objValue.constructor === Object;
}
defaultMessage(args: ValidationArguments) { // here you can provide default error
message if validation failed
const params = args.constraints[0];
if (!params.message)
return `the ${args.property} is not validate`;
else
return params.message;
}
}
要实现它,您必须在模块提供程序中添加IsKeyValueValidate:
providers: [...,IsKeyValueValidate],
并且在您的Dto:中
@IsOptional()
@Validate(IsKeyValueValidate,
[ { message:"Not valdiate!"}] )
test: Object;
我建议注意自定义验证器。在验证期间,它可以访问已验证对象的所有属性和值。
您可以将所有验证参数作为第二个参数传递,并在验证器内部使用它们来控制流。
export class Post {
@Validate(CustomTextLength, {
keyType: String,
maxLength: 20
...
})
title: string;
}