Skip to content

feature: How to Assign Validation Result to a Field Using class-validator in NestJS? #2598

Open
@cppleon

Description

@cppleon

I am working on a NestJS project where I use class-validator to validate incoming DTOs. I have a custom validator @IsAccessPointExists() that checks if an access point exists in the database. The validation works fine, but I also want to assign the validated access point object (retrieved from the database) to the accessPoint field in the DTO after validation. I want to avoid making an extra database query to fetch the access point after validation.

Here is my current DTO:

export class CompleteInstallationDto {
  @IsMongoId()
  @IsAccessPointExists()
  accessPoint: string; // I want this to hold the validated access point object
}

And here is my custom validator:

@ValidatorConstraint({ async: true })
@Injectable()
export class IsAccessPointExistsConstraint
  implements ValidatorConstraintInterface
{
  constructor(private readonly accessPointService: AccessPointService) {}

  async validate(value: string): Promise<boolean> {
    const accessPoint = await this.accessPointService.findById(value);
    return !!accessPoint; // Validation works fine
  }

  defaultMessage(): string {
    return 'Access point does not exist';
  }
}

export function IsAccessPointExists(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsAccessPointExistsConstraint,
    });
  };
}

I want the accessPoint field in the DTO to hold the validated access point object (retrieved from the database) instead of just the ID. Is there a way to achieve this using class-validator or class-transformer? If not, what would be the best approach to handle this?

Any help or suggestions would be greatly appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions