Search code examples
node.jstypescriptnestjstypeormdto

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


I need to allow the user to enter the property name in both upper and lower cases. For example,

DTO:

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

export class DicomDto {

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

Here I want the user can give input as both '7fe0,0010' or '7FE0,0010'. But the user should enter only one case either '7fe0,0010' or '7FE0,0010', not both at same time.

For example, input should be,

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

but input should not be,

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

Could you please help me is there any chance.


Solution

  • you can make custom validation decorator 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);
            },
          },
        });
      };
    }
    

    use:

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

    class validator will throw an error if both fields are present or absent