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

Easy way to compose ORed validators #2466

Open
JensRantil opened this issue Apr 25, 2024 · 1 comment
Open

Easy way to compose ORed validators #2466

JensRantil opened this issue Apr 25, 2024 · 1 comment
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.

Comments

@JensRantil
Copy link

Background

I am validating that a string is either a MongoId or a UUID. I had to implement my own validator for this:

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

@ValidatorConstraint()
export class IsUUIDOrMongoIdConstraint implements ValidatorConstraintInterface {
  validate(text: string): boolean {
    return isUUID(text) || isMongoId(text);
  }

  defaultMessage(): string {
    return 'Text ($value) must be a UUID or a MongoId';
  }
}

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

A workaround is also a somewhat complex RegExp, but that doesn't work in all cases where you want to compose different validators.

Proposed solution

Dream scenario would be to to be able to compose different validators, similar to how applyDecorators(...) works. I am thinking of something like this:

import ...

export class MyOwnDto {
  @ValidateOr(
    IsUUID(),
    IsMongoId(),
  )
  readonly myProperty: string;
}

Or something like this:

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

export function IsUUIDOrMongoId() {
  return applyValidators(
    IsUUID(),
    IsMongoId(),
  );
}
@JensRantil JensRantil added flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features. labels Apr 25, 2024
@JensRantil
Copy link
Author

This came out of nestjs#390.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.
Development

No branches or pull requests

1 participant