Nodejs, an unknown value was passed to the validate function, But I Cant find whats wrong with

Viewed 4059

Thank you for stopping by for help. I have API woring on using NodeJs, It has 3 arguments It accepts, but It seems like there is an issue on validation. When I call the API, It gives me this result,

[{
  "statusCode": 400,
  "message": [
    "an unknown value was passed to the validate function"
  ],
  "error": "Bad Request"
}]

Help me anyone can tell what's wrong with this!

I put three arguments, in order of,

  • https://www.youtube.com/watch?v=C5Y3fpHg45U
  • 1
  • JP

and there goes my code

  /**
   * Gets Subtitle From Youtube
   * @param getYoutubeSubtitleDto
   */
  public async getSubtitle(
    getYoutubeSubtitleDto: GetYoutubeSubtitleDto,
  ): Promise<Subtitle[]> { 
    const { videoId, lang, projectId } = getYoutubeSubtitleDto
    return this.getOrCreateSubtitles(videoId, lang, projectId)
  }
export class GetYoutubeSubtitleDto extends Video {
  @ApiProperty()
  @IsNumber()
  @Type(() => Number)
  projectId: number

  @ApiProperty({ description: 'Translation Language' })
  @IsString()
  lang: string
}

export const YOUTUBE_LINK_REGEX = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/

export class Video {
  @ApiProperty({ description: 'Youtube Link' })
  @IsString()
  @Matches(YOUTUBE_LINK_REGEX)
  video: string

  public get videoId(): string { 
    return YOUTUBE_LINK_REGEX.exec(this.video)[1]
  }
}
2 Answers

Set your forbidUnknownValues flag to false in main.ts/bootstrap/useGlobalPipes

app.useGlobalPipes(
    new ValidationPipe({
      forbidUnknownValues: false
    }),
  );

You must use whitelist in combination with forbidNonWhitelisted,

References:

we can whitelist the acceptable properties, and any property not included in the whitelist is automatically stripped from the resulting object

Alternatively, you can stop the request from processing when non-whitelisted properties are present, and return an error response to the user. To enable this, set the forbidNonWhitelisted option property to true, in combination with setting whitelist to true

This works for me:

<ValidationOptions> {
  forbidNonWhitelisted: true,
  whitelist: true,
}

NestJS has a section about this here.

Related