Created
April 14, 2024 11:49
-
-
Save rchaser53/3e27be97cb7962af767ea7b1daae15d6 to your computer and use it in GitHub Desktop.
class-validator nested
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { IsNotEmpty, ValidateNested, IsString, validate } from 'class-validator' | |
import { plainToInstance, Type } from 'class-transformer'; | |
import 'reflect-metadata'; | |
class Hoge { | |
@IsNotEmpty() | |
@IsString() | |
id: string; | |
// @Typeを使ってclassのinstanceにする必要がある | |
@Type(() => Fuga) | |
@IsNotEmpty() | |
@ValidateNested() | |
a: Fuga; | |
} | |
class Fuga { | |
@IsNotEmpty() | |
@IsString() | |
nyan: string; | |
} | |
const fuga = new Fuga(); | |
fuga.nyan = "s" | |
const obj = { | |
id: "sfds", | |
a: { | |
nyan: "ss" | |
} | |
} | |
const a = plainToInstance(Hoge, obj); | |
console.log(a) | |
;(async () => { | |
const ret = await validate(a) | |
console.log(ret) | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment