【问题标题】:NestJS class validator doesn't validate the dataNestJS 类验证器不验证数据
【发布时间】:2021-02-03 00:45:46
【问题描述】:

类验证器在 nestjs 应用程序中不起作用。请帮忙!谢谢!

DTO:

import {
  IsNotEmpty,
  IsDate,
  IsDateString,
  IsMobilePhone,
  IsISO8601,
  IsBoolean,
  IsEmail,
  MaxLength,
} from 'class-validator';

    export class UserEducationDto {
      @IsBoolean()
      degree: boolean;
    
      subjectMajor: string;
      subjectMinor: string;
      yearOfPassing: string;
      obtainedMarks: string;
      marksType: string;
      grade: string;
      institute: string;
      instituteAddress: string;
      instituteContactNo: string;
      instituteEmail: string;
      university: string;
      universityRegNo: string;
      universityRollNo: string;
      id?: string;
      education?: object;
      userId?: string;
    }

控制器:

@Post('/education')
  @ApiHeader({
    name: 'userId',
    description: 'userId',
  })
  async addEducationDetails(
    @Body() profileData: object,
    @GetUser() userId: any,
  ) {
      let profileDetails = new UserEducationDto();
    }

main.ts: 我加了app.useGlobalPipes(new ValidationPipe());

它仍然不验证并抛出任何与错误相关的消息。

【问题讨论】:

    标签: typescript nestjs class-validator


    【解决方案1】:

    您正在自己构建对象,因此除非您手动调用它,否则不会进行验证。该类型必须用于操作的输入参数,以便框架构建并验证它。

    比如:

    async addEducationDetails(
        @Body() profileData: UserEducationDto, // <- this
        @GetUser() userId: any,
    )
    

    【讨论】:

    • 我正在传递一个动态对象,在这种情况下如何进行?
    • @ShreyasMurali “动态对象”是什么意思?
    • 我的意思是动态 json 对象。
    • 这通常是您发送给这样的 API 的内容,Nest 应该可以处理得很好。这就是拥有验证管道的全部意义,将一些 JSON 转换为经过验证的类实例。
    猜你喜欢
    • 2022-08-02
    • 1970-01-01
    • 2021-11-17
    • 2021-03-09
    • 2019-08-29
    • 2020-05-07
    • 2019-05-16
    • 2020-09-09
    • 2020-08-09
    相关资源
    最近更新 更多