Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
  }
}
like image 237
pearllv Avatar asked Dec 21 '25 02:12

pearllv


1 Answers

For anyone looking for a proper solution and an explanation rather than just a solution that bypasses the error...

This error happens when you have registered a global ValidationPipe:

/* main.ts */
app.useGlobalPipes(new ValidationPipe())

or a local (on endpoint level):

@Post()
@UsePipes(new ValidationPipe({ transform: true }))
async save(@Query() dto: SomeDto) { ... }

In this case NestJS validate request parameters and if it doesn't match the specified type you will get error saying:

"an unknown value was passed to the validate function".

In most cases your request includes some additional data that is not expected/defined in the endpoint signature, or you are just missing a proper type information on DTOs or classes that are expected as input types.

For instance if you have a function in controller, defined like this:

@Get('/list')
async getList(@Query() dto: MyDto): Promise<List> {
  return this.listService.getList(dto);
}

// ...

class MyDto {
  @IsString()
  name: string;

  @IsString()
  surname: string;
}

and you'll pass in the {name: 'A', surname: 'B', age: 42}, you will get an error since age is not expected to be passed in.

Sometimes finding those errors can be time consuming and one simple trick to help you out is to implement your custom exceptionFactory and pass it to ValidationPipe where you can print out the error which includes some additional metadata:

/* main.ts */
app.useGlobalPipes(new ValidationPipe({exceptionFactory: (e) => {
    console.error(e);
    throw new BadRequestException('You shall not pass!');
  }
}))

This won't solve your problem but will at least give you an information which type is not correct and you can start from there.

Recommended solution

If you are sure that you are passing correct payload, but do not want to set forbidUnknownValues like other suggested, then most likely one or more of your class/DTO is most likely lacking some type declarations that are needed for successful validation of payload. For me, most of the time I was missing a proper type definitions for nested (non-primitive) properties, or for an arrays of objects.

import {IsString, ValidateNested} from 'class-validator';
import {Type} from 'class-transformer';

//...

// Primitive type
@IsString()
name: string;

// Nested objects
@Type(() => Coach)
coach: Coach;

// Validate array of objects/entities
@ValidateNested({ each: true })
@Type(() => Player)
players: Player[];

You can read more about request validation in Validation chapter in documentation.

like image 113
metodribic Avatar answered Dec 23 '25 16:12

metodribic