Search code examples
validationnestjsclass-validator

How to use class-validator validate Date is older than now and unique key in an array?


Using class-validator with Nest.js. I want to validate these two cases:

  1. Validate the input date is older than now, then give a message: Date can't before than now.
    @Field(() => Date, { description: 'Due Date' })
    dueDate: Date;
  1. Validate if all of the keys are unique in an array. But this way only can check if the ID is uuid. Is it possible to check if the IDs are the same in the array? Ex: ['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[];

Solution

    1. I searched and couldn't find a suitable inheriting validation decorators. You can custom validation classes like this:
    @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.