class-validator
class-validator copied to clipboard
question: how to validate objects with a wildcard?
I am trying to find a way to validate a class, that can have multiple names for objects
export class MailConfig {
@IsOptional()
@ValidateNested()
@Type(() => SubjectConfig)
mailingSubjects*: SubjectConfig;
}
SubjectConfig
is the configuration for this object and it can be there multiple times in my class i.e. mailingSubjectDe
mailingSubjectEn
...
How can i do this?
You can't have class properties with wildcards in their name. That's a limitation in typescript/javascript (as far as I know, at least).
It seems to me like you may want to work with this data in a non-class data structure, such as a Record<string, SubjectConfig>
. That way you could validate the keys of the record manually.
You could also rewrite your code to something like this:
export class SubjectConfigWithName extends SubjectConfig {
@IsString() // or validate the name with your own regex?
name: string; // e.g. 'subjectConfigDe' or maybe just 'de'?
}
export class MailConfig {
@IsOptional()
@ValidateNested({each: true})
@Type(() => SubjectConfigWithName[]) // I don't know what this decorator is but I guess this would be correct
subjectConfigs: SubjectConfigWithName[];
}
This way you can just pass in however many config objects you want. They can have unique names that can be validated however you want inside SubjectConfigWithName
If you have to do this just as you described I would just type it out:
export class MailConfig {
@IsOptional()
@ValidateNested()
@Type(() => SubjectConfig)
mailingSubjectsDe: SubjectConfig;
@IsOptional()
@ValidateNested()
@Type(() => SubjectConfig)
mailingSubjectsEn: SubjectConfig;
// and so on...
}
Have you looked at my reply, @Thomas-1985?
Is this issue still relevant? If not, feel free to close it :)
Yes thanks a lot, this is indeed helpful. Ill close this one :)
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.