Currently, I am utilizing TypeORM and seeking ways to dynamically set the validation fields based on the value of another field. Let me illustrate this using my DTO model:
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;
}
An issue arises with the validation field within modelCreate as it can vary in structure and properties when stored in the database:
validation: {
required: true,
text: 2
}
or may appear like this:
validation: {
required: false,
number: 1,
maxNumber: 10
}
This variability is dependent on the type property within modelCreate. For example, if the type is 'TIME', the desired validation would be:
BaseValidation {
@IsBoolean()
required: true,
@IsString()
text: 2
}
Conversely, if the type is 'NUMBERS', the expected validation format changes to:
BaseValidation {
@IsBoolean()
required: boolean,
@IsNumber()
number: number,
@IsNumber()
maxNumber: number
}
The main query revolves around how to switch between different classes in the validation field based on the value of the type field within class validator, and whether such a functionality is feasible.