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

Why not do some auto transform in decorator validation?

Open ruiming opened this issue 9 years ago • 2 comments

Sometime I want to use an interface to validate both body or queryParams. But there only exist string type in queryParams which make some decorators such as @IsNumber always validate failure. So I have to write a custom validator to validate and meantimes not breaking body validation. For example:

export function IsNumber (validationOptions?: ValidationOptions) {
  return (object: Object, propertyName: string) => {
    registerDecorator({
      name: 'IsNumber',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate (value: any, args: ValidationArguments) {
          const type = Reflect.getMetadata('design:type', args.object, args.property)
          if (type === Number && typeof value === 'string') {
            value = parseInt(value, 10)
          }
          return typeof value === 'number' && !isNaN(value)
        },
        defaultMessage () {
          return 'Must be a number or string that can be parsed into number'
        }
      }
    })
  }
}

In this decorator, '10', 10' can both pass the validation, and will auto be transformed into 10 if value is '10'. I think it is ok to do such auto transform in decorator. Or maybe an option to do so? What do you think?

ruiming avatar Jun 26 '17 11:06 ruiming

Hi @ruiming , I do query parameters validation and I found your same issue. You need to define your field on your dto as type number:

@IsInt()
@Type(() => Number)
public year: number;

You can import "Type" from class-transformer library.

With this added, you onlye have to call the method:

const object = plainToClass(classType, rawDto);

Before your validation.

Cheers!

ericzon avatar Jan 08 '18 14:01 ericzon

Great, thank you guy.

ruiming avatar Jan 08 '18 15:01 ruiming