class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: how to validate objects with a wildcard?

Open Thomas-1985 opened this issue 2 years ago • 1 comments

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?

Thomas-1985 avatar May 28 '22 22:05 Thomas-1985

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...
}

braaar avatar Aug 09 '22 16:08 braaar

Have you looked at my reply, @Thomas-1985?

Is this issue still relevant? If not, feel free to close it :)

braaar avatar Aug 16 '22 07:08 braaar

Yes thanks a lot, this is indeed helpful. Ill close this one :)

Thomas-1985 avatar Aug 16 '22 09:08 Thomas-1985

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.

github-actions[bot] avatar Sep 16 '22 00:09 github-actions[bot]