简体   繁体   English

打字稿。 - 如何使用类验证器和类转换器(Nestjs)验证子类中的特定字段

[英]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我正在尝试使用类验证器和类转换在 Nestjs 中处理基本调用

I have a base class as follows:我有一个基类,如下所示:

class BaseClass{
   @IsString()
   name:string;

   @IsNumber()
   num:number;
}

now I have a service that should get childDto现在我有一个应该得到 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现在我想要一个只包含“名称”并在控制器或服务中验证的 dto

class childDto extends BaseClass{}

how can I make sure to take only "name" field instead, create another dto with code duplication我怎样才能确保只取“名称”字段,而是创建另一个带有代码重复的 dto

and also to make sure the validation is working per specific DTO并确保验证按照特定的 DTO 工作

thx谢谢

You can use PickType您可以使用 PickType

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

For more details visit mapped-types#pick有关更多详细信息,请访问映射类型#pick

I think syntax planToClass err please check again我认为语法 planToClass 错误,请再次检查
example: let users = plainToClass(User, userJson);示例: let users = plainToClass(User, userJson);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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