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

feat: new IsMongoIdObject validator

Open desmap opened this issue 4 years ago • 3 comments

Description

  1. @IsMongoId() just checks if it is a string (see below, taken from your code base) where you could have used ObjectId.isValid() from the mongodb or bson repo.
  2. Is this repo still maintained?
export function isMongoId(value: unknown): boolean {
    return typeof value === "string" && validator.isMongoId(value);
}

Reproduction

Create a Mongo Id with new ObjectId() and you'll get an error when validating. Can't provide any sandbox. Tried Stackblitz and CodeSandbox but they can't get bson or mongodb running. So you have try yourself in you IDE:

import { IsMongoId, validateSync } from 'class-validator'
import { ObjectId } from 'mongodb'

class A {
  @IsMongoId()
  _id = new ObjectId()
}

console.log(validateSync(new A()))

Environment

  • [ ] nodejs: 14.4
  • [ ] browser: not relevant
  • [ ] framework/library: nothing

class-validator version: 0.12.2

desmap avatar Jun 10 '20 08:06 desmap

Hello, I think this is the intended behaviour, most of the decorator are under the "String validation decorators" section in the readme.

Internally this library use validator.js to perform validation and as you can see it's "A library of string validators and sanitizers".

It's wrong to say that it just checks if it is a string because as you can see from the code you quote we also do the validator.js check. && validator.isMongoId(value);. You can find the underlying code at this url. It check if it's an hexadecimal string of lenght 24. If this is not the right behavior you can open an issue upstream but using mongodb or bson to do object validation seem out of scope since it's a string validation library.

However you can probably do what you want with class-validator using custom validation decorator (link to the doc)

I did not test but It would look something along the line of:

import {registerDecorator, ValidationOptions, ValidationArguments} from "class-validator";
import { ObjectId } from "bson"

export function IsMongoIdObject(validationOptions?: ValidationOptions) {
   return function (object: Object, propertyName: string) {
        registerDecorator({
            name: "IsMongoIdObject",
            target: object.constructor,
            propertyName: propertyName,
            constraints: [],
            options: validationOptions,
            validator: {
                validate(value: any, args: ValidationArguments) {
                    return ObjectId.isValid(value)
                }
            }
        });
   };
}

then use it as:

class A {
  @IsMongoIdObject()
  _id = new ObjectId()
}

Kiliandeca avatar Jun 17 '20 21:06 Kiliandeca

Thanks. I saw that I can create a custom validator, so this should do the job for now.

I think this is the intended behaviour, most of the decorator are under the "String validation decorators" section in the readme.

IDK, following your logic (it's in a 'string' subfolder + the upstream repo isn't doing more) you might be right. But from a user's view who just ESM-imports { IsMongoId } without reading the sources or folder structures too much, he/she assumes and expects it's the original validator function from the bson lib. So, this might be intended from your side but it's still misleading.

desmap avatar Jul 02 '20 19:07 desmap

I think it shouldn't be directly in the class-validator as it serves a specific scope. But instead, Type decarator can be added, just like in the class-transformer package.

With class-transformer we can do this:

import { ObjectId } from "mongodb"
import { Type } from "class-transformer"

export class MyBestDto {
    @Type(() => ObjectId)
    id: string;
}

A use like this is more comfortable and more general.

9ssi7 avatar Aug 04 '22 19:08 9ssi7

import { IsMongoId } from 'class-validator';

export class DeleteCategoryDto {
  @IsMongoId({ message: '_id not valid!!' })
  _id: string;
}

ahmad118128 avatar Oct 29 '22 09:10 ahmad118128

This is an old issue without new activity. Closing as expired.

NoNameProvided avatar Dec 09 '22 21:12 NoNameProvided

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Jan 09 '23 00:01 github-actions[bot]