简体   繁体   中英

typescript.- how can I validate specific fields in child class using class validator and class transformer (Nestjs)

I am trying to working with base calls in Nestjs with class-validator and class-transform

I have a base class as follows:

class BaseClass{
   @IsString()
   name:string;

   @IsNumber()
   num:number;
}

now I have a service that should get childDto

service....
async fun(child:childDTO){

  const dto = plainToClass(child)
  await validate(dto)// or via validate pipe
}

now I would like a dto that includes only the "name" and validate in the controller or service

class childDto extends BaseClass{}

how can I make sure to take only "name" field instead, create another dto with code duplication

and also to make sure the validation is working per specific DTO

thx

You can use PickType

export class childDto extends PickType(BaseClass, ['name'] as const) {}

For more details visit mapped-types#pick

I think syntax planToClass err please check again
example: let users = plainToClass(User, userJson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM