typescript - class validator - validate based on different type

Viewed 4489

I'm working with TypeORM, and I would like to provide different to field based on other field value. So to explain, here is how my DTO model looks:

import { IsString, IsOptional, IsNumber, IsEnum, IsObject, IsBoolean, ValidateNested } from 'class-validator';

export enum AttributeTypes {
    DATE = 'DATE',
    TIME = 'TIME',
    NUMBERS = 'NUMBERS',
}

export class BaseValidation {
    @IsOptional()
    @IsBoolean()
    required: boolean;
}

export class modelCreate {
    @IsOptional()
    @IsNumber()
    id: number;

    @IsOptional()
    @IsString()
    label: string;

    @IsOptional()
    @IsEnum(AttributeTypes)
    type: AttributeTypes;

    @IsOptional()
    @IsObject()
    @ValidateNested()
    validation: BaseValidation;
}

The problem here is that I have this field: validation in modelCreate, & that field is an object and can have multiple properties & can look like this in db:

validation: {
   required: true,
   text: 2
}

or it can look like this:

   validation: {
       required: false,
       number: 1,
       maxNumber: 10
    }

and that would depend on type property of modelCreate, because if type is 'TIME', I would like to have validation for this:

BaseValidation {
    @IsBoolean()
     required: true,
    @IsString()
    text: 2
}

and if type is 'NUMBERS', I would like to have validation like this

  BaseValidation {
           @IsBoolean()
           required: boolean,
           @IsNumber()
           number: number,
           @IsNumber()
           maxNumber: number
        }

So the question is how would I toogle different classes in validation field based on type field value in class validator, and is that even possible ?

1 Answers

for that you need to create 2 classes, for every case, string and numbers. Then change the type validation: StringBaseValidation | NumberBaseValidation; now class-validator can distinguish the cases.

If the data comes from a request you need to use @Type((obj) => obj.writeConditionToDetectString ? StringBaseValidation : NumberBaseValidation) to help the lib to understand which type is the data from the request.

Related