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

feature(SatisfyAny): add a validator to ensure given value satisfies any of constraint functions, in order to validate Union Type, etc #2575

Open
qwertycxz opened this issue Jan 18, 2025 · 0 comments
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.

Comments

@qwertycxz
Copy link

Description

To validate a union type, the user has to make Custom validation, which is not very convenient for such a commonly used type.

Proposed solution

I wrote a SatisfyAny.ts. It works well:

import { ValidationOptions } from '../ValidationOptions';
import { buildMessage, ValidateBy } from './ValidateBy';

export const SATISFY_ANY = 'satisfyAny';

/**
 * Checks if given value satisfies any of the validators.
 */
export function satisfyAny(value: unknown, validators: readonly ((value: unknown) => boolean)[]): boolean {
  return validators.some(validator => validator(value));
}

/**
 * Checks if given value satisfie any of the validators.
 */
export function SatisfyAny(values: readonly ((value: unknown) => boolean)[], validationOptions?: ValidationOptions): PropertyDecorator {
  return ValidateBy(
    {
      name: SATISFY_ANY,
      constraints: [values],
      validator: {
        validate: (value, args): boolean => satisfyAny(value, args?.constraints[0]),
        defaultMessage: buildMessage(
          eachPrefix => eachPrefix + '$property must satisfy one of the following validators: $constraint1',
          validationOptions
        ),
      },
    },
    validationOptions
  );
}

Usage

import {
    isBoolean,
    IsNotEmpty,
    isString,
    SatisfyAny,
} from "class-validator";

class LanguageConfig {
    @SatisfyAny([isBoolean, isString])
    @IsNotEmpty()
    shell!: boolean | string;
}
@qwertycxz qwertycxz added flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features. labels Jan 18, 2025
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