You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Class Validator支持占位符属性名验证?

解决Class Validator处理动态占位符属性名的验证问题

装饰器无法直接应用在TypeScript的索引签名上,这是你遇到Decorators are not valid here错误的核心原因。下面提供两种解决方案,既能满足验证需求,也可根据情况选择是否保留SimpleOperatorValue类。

方案一:保留SimpleOperatorValue类

不能直接给索引签名加装饰器,我们可以调整SimpleOperatorValue的结构,把验证逻辑绑定到具体属性上,再结合Class Validator的嵌套验证能力处理动态键值对:

  1. 重构SimpleOperatorValue类:
import { IsNotEmpty } from 'class-validator';

export class SimpleOperatorValue implements ISimpleOperatorValue {
  @IsNotEmpty()
  value: TypeValueOperator;
}
  1. 在SimpleOperator中配置嵌套验证:
import { ValidateNested, Type } from 'class-validator';

export class SimpleOperator implements ISimpleOperator {
  @ValidateNested({ each: true })
  @Type(() => SimpleOperatorValue)
  value: Record<string, SimpleOperatorValue>;
}

这个写法会自动遍历value对象的所有属性,验证每个SimpleOperatorValue实例的value属性不为空。

方案二:直接验证动态对象(无需SimpleOperatorValue)

如果不需要保留SimpleOperatorValue类,可以通过自定义验证器来校验动态对象的所有值:

  1. 创建自定义验证器约束:
import { Validate, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'allValuesNotEmpty', async: false })
export class AllValuesNotEmptyConstraint implements ValidatorConstraintInterface {
  validate(obj: Record<string, TypeValueOperator>, args: ValidationArguments) {
    if (typeof obj !== 'object' || obj === null) return false;
    // 可根据实际需求调整空值判断逻辑
    return Object.values(obj).every(val => val !== undefined && val !== null && val !== '');
  }

  defaultMessage(args: ValidationArguments) {
    return `所有属性值不能为空`;
  }
}
  1. 在SimpleOperator中使用自定义验证器:
import { IsObject } from 'class-validator';
import { AllValuesNotEmptyConstraint } from './your-validator-path';

export class SimpleOperator implements ISimpleOperator {
  @IsObject()
  @Validate(AllValuesNotEmptyConstraint)
  value: { [key: string]: TypeValueOperator };
}

内容的提问来源于stack exchange,提问作者Asaf Alroy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:00:12