如何在 nest.js DTO 中同时允许大写和小写

How to allow both uppercase and lowercase in nest.js DTO

我需要允许用户以大写和小写形式输入 属性 名称。 例如,

DTO:

import { ApiProperty } from "@nestjs/swagger";
import { IsDefined, Validate } from "class-validator";

export class DicomDto {

    @ApiProperty({ description: 'Image data' })
    @IsDefined()
    '7fe0,0010'?: string;
    
}

我希望用户可以输入“7fe0,0010”或“7FE0,0010”。但是用户应该只输入一种情况 '7fe0,0010' 或 '7FE0,0010',不能同时输入两种情况。

例如, 输入应该是,

{
  '7fe0,0010': "imagedata" or '7FE0,0010': "imagedata"
}

但输入不应该,

{
  '7fe0,0010': "imagedata",
  '7FE0,0010': "imagedata"
}

有没有机会请你帮帮我。

您可以制作自定义验证装饰器 XOR

import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function XOR(property: string, validationOptions?: ValidationOptions) {
  return function(object: Object, propertyName: string) {
    registerDecorator({
      name: 'xor',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [relatedPropertyName] = args.constraints;
          const relatedValue = (args.object as any)[relatedPropertyName];
          return Boolean(!!value ^ !!relatedValue);
        },
      },
    });
  };
}

使用:

export class DicomDto {
    @ApiProperty({ description: 'Image data' })
    @XOR('7FE0,0010')
    '7fe0,0010'?: string;

    @ApiProperty({ description: 'Image data' })
    @XOR('7fe0,0010')
    '7FE0,0010'?: string;
    
}

class 如果两个字段都存在或不存在,验证器将抛出错误