I need to validate an object where each key is an enum and each value have the same shape.
Right now I was able to validate the object by explicitly setting each key and validate each nested object, but I would like something more usable so when I need to change the enum I don't have to update the dtos too.
This is the enum I would like to use
enum Countries {
ES = 'ES',
IT = 'IT'
}
This is my actual work.
class Country {
@IsString({ each: true })
@IsOptional()
readonly region?: string[];
@IsString({ each: true })
@IsOptional()
readonly province?: string[];
@IsString({ each: true })
@IsOptional()
readonly zipcode?: string[];
}
class Locations {
@IsObject()
@ValidateNested()
@Type(() => Country)
@IsOptional()
readonly ES?: Country;
@IsObject()
@ValidateNested()
@Type(() => Country)
@IsOptional()
readonly IT?: Country;
}
export class CreateDto {
... other props
@IsObject()
@ValidateNested()
@Type(() => Locations)
@IsOptional()
readonly locations?: Locations;
}
As you can see if I add a new country to the enum I have to update the class Locations
with the corresponding prop.
## Example Payload
{
... other props
locations: {
IT: {
region: ['Lazio']
}
}
}