Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate array of uuid in nest js using class validator?

How to validate an array of uuid ? I'm using the pre-built ParseArrayPipe to validate the payload array structure.

@Post(':id/players')
  addPlayers(
    @Body(new ParseArrayPipe({ items: GamePlayerDto, separator: ',' }))
    gamePlayers: GamePlayerDto,
  ) {
    console.log(gamePlayers);
  }
export class GamePlayerDto {
  @IsUUID()
  playerId!: string;
}

I don't want class validator to check if playersId property is here but only raw value

e.g. this is what my server should received

["73aef2dd-c227-4774-b547-b3117b543863", "73aef2dd-c227-4774-b547-b3117b543863"]
like image 391
soyuz Avatar asked Feb 03 '26 00:02

soyuz


2 Answers

You have to set the option - "each: true".

export class GamePlayerDto {
  @IsUUID(UUIDVersion,{each:true})
  playerId!: string;
}

Accepted UUID Version values - '3' | '4' | '5' | 'all' | 3 | 4 | 5;

Quoting official doc - "Specifies if validated value is an array and each of its items must be validated."

Essentially, The value of playerId is considered as an array and is of type UUID (of specified version) and each value has to be validated.

UPDATE

Also update your request handler to:

@Post(':id/players')
  addPlayers(
    @Body(ValidationPipe))
    gamePlayers: GamePlayerDto,
  ) {
    console.log(gamePlayers);
  }

ValidationPipe is a default pipe in NestJS that works hand in hand with class validator. It will validate the incoming request body/params etc.. and rejects if it does not meet the set conditions in the DTO.

like image 116
SPS Avatar answered Feb 05 '26 14:02

SPS


you can use it

@IsUUID(undefined, {each:true})
providers: string[]
like image 23
erfan seidipoor Avatar answered Feb 05 '26 14:02

erfan seidipoor