typestack / class-validator

Decorator-based property validation for classes.
MIT License
11.02k stars 800 forks source link

fix: @IsUUID() not working #2122

Open MansourWolou opened 1 year ago

MansourWolou commented 1 year ago

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

edilson commented 1 year ago

@MansourWolou which UUID version you're using?

kpkonghk01 commented 1 year ago

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);
  });
strongpauly commented 1 year ago

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?

kpkonghk01 commented 1 year ago

@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

tjhiggins commented 1 month ago

Looks like a pr got merged to add support for rfc9562 (nil etc), but validatorjs hasn't cut a release yet: https://github.com/validatorjs/validator.js/blob/ff56dcf5ad16abc4127528eafae559ac716863fb/src/lib/isUUID.js#L13