class-validator
class-validator copied to clipboard
question: How to validate nested arrays when the elements are from different classes?
I use nestjs with class-validator, and I have the following case:
- Two classes with same field name that has different types:
class A {
@IsDefined()
field: number;
}
class B {
@IsDefined()
field: string;
}
- Third class that has array of elements from types A or B, my problem is how to validate each array member against its own class:
class C {
@ValidateNested({ each: true })
@Type(I_DON'T_KNOW_WHAT_TO_DO_HERE)
array: (A | B)[];
}
How can I validate the array?
Thanks ahead!
same
request:
{
"nickname": "NickName",
"sign": "Sign",
"content": "Content",
"links": {
"github": "github",
"youtube": "youtube",
}
}
DTO
class LinksDto {
@IsString()
@MaxLength(39)
@IsNotEmpty()
public github: string
@IsString()
@MaxLength(39)
@IsNotEmpty()
public youtube: string
}
class AccountsDto {
@IsString()
@MaxLength(16)
@IsNotEmpty()
public nickname: string;
@IsString()
@MaxLength(60)
public sign: string;
@IsString()
@MaxLength(150)
public content: string;
@ValidateNested()
public links: LinksDto
}
Logs
An instance of AccountInfoDto has failed the validation:
- property links.github has failed the following constraints: whitelistValidation
- property links.youtube has failed the following constraints: whitelistValidation
errors[0].children
[
ValidationError {
target: {
github: 'github',
youtube: 'youtube',
},
value: 'github',
property: 'github',
children: undefined,
constraints: { whitelistValidation: 'property github should not exist' }
},
ValidationError {
target: {
github: 'github',
youtube: 'youtube',
},
value: 'youtube',
property: 'youtube',
children: undefined,
constraints: { whitelistValidation: 'property youtube should not exist' }
},
]
response:
property github should not exist, property youtube should not exist
Maybe this will work. @Cha-Shao
import { Type } from 'class-transformer';
@ValidateNested()
@Type(()=>LinksDto)
links: LinksDto
@elad30300 Hi, I came across your question. Quite a lot of time has passed since the creation, but maybe it will be useful to someone in the future.
class C {
@ValidateNested({ each: true })
@Type(null, {
keepDiscriminatorProperty: true,
discriminator: {
property: 'type',
subTypes: [
{
name: 'A',
value: A,
},
{
name: 'B',
value: B,
},
],
},
})
array: (A | B)[];
}
@smoothbronx I have this error Argument of type 'null' is not assignable to parameter of type '((type?: TypeHelpOptions | undefined) => Function) | undefined'