Search code examples
javascriptnode.jsnestjsclass-validator

Dto custom validation


How do I validate my timestamp at DTO level? I need trackingEndTimestamp to be greater than trackingStartTimestamp:

import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsNumber, IsString, Validate } from "class-validator";
import { CustomTextLength } from "./CustomTextLength";

export class UserActivityDto {
  @ApiProperty()
  @IsNotEmpty()
  userId: number;

  @ApiProperty()
  @IsNotEmpty()
  @IsString()
  loginId: string;

  @ApiProperty()
  @IsNotEmpty()
  @IsNumber()
  trackingStartTimestamp: number;

  @ApiProperty()
  @IsNotEmpty()
  @IsNumber()
  @Validate(CustomTextLength, [trackingStartTimestamp, 20], {
    message: "End date cannot be greater then end date",
  })
  trackingEndTimestamp: number;
}

Here at @validate I want to pass trackingStartTimestamp value as a parameter

plz Suggest


Solution

  • You don't need to pass it, you can find it in the validate handler.

    validate(value: any, validationArguments?: ValidationArguments) {
      console.log(validationArguments.object.trackingStartTimestamp );
    }