class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

Option to force validation even skipMissingProperties set to true

Open zhenwenc opened this issue 6 years ago • 2 comments

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!

zhenwenc avatar Mar 30 '19 22:03 zhenwenc

@zhenwenc did you manage to get around this issue?

dushyant89 avatar Apr 18 '22 13:04 dushyant89

Any resolution for achieving this?

sebastiantf avatar Sep 14 '23 13:09 sebastiantf