class-validator
class-validator copied to clipboard
New decorators @Custom and @Transform
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?
I agree with @Custom
, so much work is necessary to create a custom decorator.
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.
Great idea! I would name it @Callback
👍🏻
@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));
},
},
});
};
}
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.
Check out class-transformer and see if that doesn't satisfy your needs already.
It seems to me that @Validate
works the way @udanpe would like their @Custom
idea to work?
I now realise that what people really want is a more concise way to write custom validators. I'll admit I find the standard way of writing custom validators a bit verbose, myself.
I don't think @Transform
will make it's way, if you need that functionality use class-transformer
.
The @Custom
decorator is a good idea, it's general enough that it will be useful for many.
It expects a function that receives the data as a parameter and if the result of the function is true then validation passes and fails otherwise.
I think someone can grab and implement this, it's mostly straightforward. We may iterate on the name, but I have no better idea for now.