meightythree
meightythree

Reputation: 333

How to combine multiple class-validator constrains in Nestjs request class?

I have two validator classes NameMinLengthValidator and NameMaxLengthValidator

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'name', async: false })
export class NameMinLengthValidator implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    return !!text && 2 <= text.length;
  }

  defaultMessage(args: ValidationArguments) {
    return 'Name must be at least 2 characters.';
  }
}

@ValidatorConstraint({ name: 'name', async: false })
export class NameMaxLengthValidator implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    return !!text && text.length <= 12;
  }

  defaultMessage(args: ValidationArguments) {
    return 'Name must be max 12 characters.';
  }
}

I have to this in every class where I want to validate these constraints

export class MyRequest {
 @Validate(NameMinLengthValidator)
 @Validate(NameMaxLengthValidator)
 name: string;
}

I want to achieve something similar to this, how can I combine both validators?

export class MyRequestCombined {
 @Validate(NameLengthValidator)
 name: string;
}

Upvotes: 1

Views: 2668

Answers (1)

bebewr
bebewr

Reputation: 126

You can use NestJS built-in function to combine multiple decorators. Example from documentation

import { applyDecorators } from '@nestjs/common';

export function Auth(...roles: Role[]) {
  return applyDecorators(
    SetMetadata('roles', roles),
    UseGuards(AuthGuard, RolesGuard),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({ description: 'Unauthorized"' }),
  );
}

source: https://docs.nestjs.com/custom-decorators

Upvotes: 4

Related Questions