NestJS class validator doesn't validate the data

1.9k views Asked by At

class validator doesn't work in nestjs application. Please help! Thanks!

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;
    }

Controller:

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

main.ts: I have added app.useGlobalPipes(new ValidationPipe());

It still doesn't validate and throw any message related to error.

1

There are 1 answers

5
brunnerh On

You are constructing the object yourself, so there will be no validation unless you invoke it manually. The type has to be used on the input parameter of the action so the framework will construct and validate it.

So something like:

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