Using class-validator
with Nest.js. I want to validate these two cases:
@Field(() => Date, { description: 'Due Date' })
dueDate: Date;
['1234-1234-1234-1234', '1234-1234-1234-1234']
@Field(() => [String], { description: 'product IDs' })
@IsUUID('all', { each: true, message: 'Product ID is not valid.' })
productIds: string[];
@ValidatorConstraint()
export class IsAfterNowConstraint implements ValidatorConstraintInterface {
validate(date: Date) {
return Date.now() < date.getTime();
}
defaultMessage(args: ValidationArguments) {
return `Date ${args.property} can not before now.`;
}
}
function IsAfterNow(validationOptions?: ValidationOptions) {
// eslint-disable-next-line @typescript-eslint/ban-types
return function (object: Object, propertyName: string) {
registerDecorator({
target: object.constructor,
propertyName: propertyName,
options: validationOptions,
validator: IsAfterNowConstraint,
});
};
}
@ArrayUnique(identifier?: (o) => any)
: Checks if all array's values are unique. Comparison for objects is reference-based. Optional function can be speciefied which return value will be used for the comparsion.