Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question: How to invoke class-validator on a class itself #2512

Open
yashg32 opened this issue Aug 1, 2024 · 0 comments
Open

question: How to invoke class-validator on a class itself #2512

yashg32 opened this issue Aug 1, 2024 · 0 comments
Labels
type: question Questions about the usage of the library.

Comments

@yashg32
Copy link

yashg32 commented Aug 1, 2024

Validators are typically invoked on class variables, not on the class itself. Is it possible to apply a validator to a class? I'm trying to use a decorator as a clean solution that can also be used elsewhere. We want to define certain properties that atleast one of them should exist directly on class?

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

@ValidatorConstraint({ async: false })
export class AtLeastOneOf implements ValidatorConstraintInterface {
  validate(_, args: ValidationArguments) {
    const properties = args.constraints;
    const value = args.object as any;

    return properties.some(property => value[property] !== undefined && value[property] !== null);
  }

  defaultMessage(args: ValidationArguments) {
    const properties = args.constraints;
    return `At least one of the following properties must be provided: ${properties.join(', ')}.`;
  }
}

export function AtLeastOneField(properties: string[], validationOptions?: ValidationOptions) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      name: 'AtLeastOneField',
      target: object.constructor,
      propertyName,
      options: validationOptions,
      constraints: properties,
      validator: AtLeastOneOf,
    });
  };
}


@AtLeastOneField(['photoId', 'userId']) // not work here
export class ListUsers {
  @IsID()
  @IsOptional()
  userId?: string;

  @IsID()
  @IsOptional()
  accountId?: string;

  @IsID()
  @IsOptional()
  photoId?: string; 

}
@yashg32 yashg32 added the type: question Questions about the usage of the library. label Aug 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

1 participant