typestack / class-validator

Decorator-based property validation for classes.
MIT License
10.82k stars 781 forks source link

Option to force validation even skipMissingProperties set to true #340

Open zhenwenc opened 5 years ago

zhenwenc commented 5 years ago

Problem:

I have implemented a validation decorator to ensure a property is defined when the given condition is met:

export function IsDefinedIf<A = any, B = any>(
  condition: ConditionFunc<A, B>,
  validationOptions?: ValidationOptions
) {
  return function(type: Object, propertyName: string) {
    registerDecorator({
      name: 'isDefinedIf',
      target: type.constructor,
      propertyName: propertyName,
      constraints: [condition],
      options: validationOptions,
      validator: {
        validate(value: B, args: ValidationArguments) {
          return !condition(args.object as A, value) || !isNullish(value);
        },
        defaultMessage(_args: ValidationArguments) {
          return `${propertyName} should be defined`;
        },
      },
    });
  };
}

This decorator won't be executed when skipMissingProperties: true, which requires the same special treatment for @IsDefined.

Proposal:

Currently there is an always option in ValidationOptions:

export interface ValidationOptions {
    /**
     * Indicates if validation must be performed always, no matter of validation groups used.
     */
    always?: boolean;
}

Can we extend it to also ignores skipMissingProperties option, or create a new option.

Many thanks for the great work!

dushyant89 commented 2 years ago

@zhenwenc did you manage to get around this issue?

sebastiantf commented 11 months ago

Any resolution for achieving this?