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

New decorators @Custom and @Transform

Open udanpe opened this issue 4 years ago • 6 comments

Of course, I read how to create my own validation rules. But I am very lazy to do this, so now I use something like..

@ValidateIf(that => that.password !== that.passwordConfirmation)
@Length(1, 0, { message: 'password !== passwordConfirmation' })

It would be nice to have custom decorator

@Custom(that => that.password !== that.passwordConfirmation, { messages: ''})

And, of course, transform value before validation

@Transform(value => parseInt(value))

And, what about moving default messages to a JSON file? Now it is very difficult to localize it. Any plans for this?

udanpe avatar Jul 26 '19 08:07 udanpe

I agree with @Custom, so much work is necessary to create a custom decorator.

rolivegab avatar Jul 29 '19 19:07 rolivegab

Maybe @Custom is not bad idea. But we should avoid add decorators like @Transform as this library is about validating not about transform. Use class-transform on this purpose.

vlapo avatar Aug 10 '19 12:08 vlapo

Great idea! I would name it @Callback 👍🏻

gremo avatar Sep 12 '19 23:09 gremo

@vlapo Any progress on this?

export function ValidateCallback(
  callback: (object: Object, value: any) => Promise<boolean> | boolean,
  validationOptions?: ValidationOptions,
) {
  return (object: Object, propertyName: string) => {
    registerDecorator({
      name: 'validateCallback',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [callback],
      options: validationOptions,
      validator: {
        async validate(value: any, args: ValidationArguments) {
          const [callback] = args.constraints;
          return Boolean(await callback(args.object, value));
        },
      },
    });
  };
}

udanpe avatar Jan 18 '20 11:01 udanpe

I can see the reason for adding a @Transform validator. Let's say I do not want to have a string value transformed into INT. I just want to use a power of IsInt decorator accompanied with an int being wrapped into a string.

dawiddominiak avatar Sep 15 '22 17:09 dawiddominiak

Check out class-transformer and see if that doesn't satisfy your needs already.

braaar avatar Sep 20 '22 07:09 braaar

It seems to me that @Validate works the way @udanpe would like their @Custom idea to work?

braaar avatar Oct 03 '22 11:10 braaar