class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

fix: @IsUUID() not working

Open MansourWolou opened this issue 1 year ago • 5 comments

i have a dto `import { IsUUID } from 'class-validator';

export class idDto { @IsUUID() id: string; }a controller @Get(USER_REQUEST_MAPPING.GET_USER_BY_ID) getUserById(@Param('id', ValidationPipe) id: idDto): Promise<User | null> { return this.usersService.findById(id); } but i keep gating the saame error { "statusCode": 400, "message": [ "id must be a UUID" ], "error": "Bad Request" }

MansourWolou avatar Jun 08 '23 23:06 MansourWolou

@MansourWolou which UUID version you're using?

edilson avatar Jun 14 '23 14:06 edilson

I tested with this code, don't find any problem, could you provide your payload?

/* eslint-disable no-process-exit */
import { plainToInstance } from 'class-transformer';
import { v4 as uuidV4 } from 'uuid';
import { IsUUID, validate } from 'class-validator';

class IdDto {
  @IsUUID()
  id: string;
}

(async () => {
  const idInstance = plainToInstance(IdDto, { id: uuidV4() });
  console.log(idInstance); // IdDto { id: '2d6de19c-363a-439a-bd0b-9f47553ab345' }
  console.log(await validate(idInstance)); // []

  const idInstance2 = plainToInstance(IdDto, { id: '123' });
  console.log(idInstance2); // IdDto { id: '123' }
  console.log(await validate(idInstance2));
  // [
  //   ValidationError {
  //     target: IdDto { id: '123' },
  //     value: '123',
  //     property: 'id',
  //     children: [],
  //     constraints: { isUuid: 'id must be a UUID' }
  //   }
  // ]
})()
  .then(() => {
    process.exit(0);
  })
  .catch((error) => {
    console.log(error);
    process.exit(1);
  });

kpkonghk01 avatar Jun 21 '23 04:06 kpkonghk01

I've found that an artificial uuid, like 00000000-0000-0000-0000-000000000000 doesn't pass the validation for version 4. I wonder if that's what the OP was seeing?

strongpauly avatar Aug 09 '23 08:08 strongpauly

@strongpauly The uuid you provided is not a valid uuid v4.

You can find the validation logic here: https://github.com/typestack/class-validator/blob/master/src/decorator/string/IsUUID.ts#L13

It's using another popular lib validator, here is how it judges whether an id is uuid v4: https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js#L12

/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,

The rule indicates that there're 2 digits can't be 0 :)

e.g. this one is valid: 00000000-0000-4000-8000-000000000000

kpkonghk01 avatar Sep 04 '23 15:09 kpkonghk01