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

feat: add `skipIf` predicate option to decorator options

Open aoi-umi opened this issue 3 years ago • 3 comments

Description

like this https://github.com/typestack/class-validator/issues/740

export class ContentSave {
  @IsDefined()
  @MinLength(5)
  title: string;

  @Type()
  submit?: boolean;
}

when submit is true, i want to skip IsDefined , but not minLength for example: {title: "111111111", submit: true} => valid {title: undefined, submit: false} => valid {title: "1", submit: false} => invalid(MinLength)

Proposed solution

add skipIf on the ValidationOptions

export class ContentSave {
  @IsDefined({
    skipIf: (data) => data.submit !== true
  })
  @MinLength(5)
  title: string;

  @Type()
  submit?: boolean;
}

aoi-umi avatar Dec 19 '21 13:12 aoi-umi

import type { ValidationOptions } from 'class-validator';
import { ValidateIf } from 'class-validator';

/**
 * Checks (in case of condition passed) if the value is missing and if so, ignores all validators.
 *
 * @example
 * @IsOptionalIf((o) => o && o?.source === 'instore', { always: true })
 * email: string
 */
export function IsOptionalIf(condition: (object: any, value: any) => boolean, validationOptions?: ValidationOptions): PropertyDecorator {
    return ValidateIf((object: Record<string, unknown>, value: string): boolean => {
        return !condition(object, value) ? true : value !== null && value !== undefined;
    }, validationOptions);
}

ruscon avatar Dec 24 '21 13:12 ruscon

import type { ValidationOptions } from 'class-validator';
import { ValidateIf } from 'class-validator';

/**
 * Checks (in case of condition passed) if the value is missing and if so, ignores all validators.
 *
 * @example
 * @IsOptionalIf((o) => o && o?.source === 'instore', { always: true })
 * email: string
 */
export function IsOptionalIf(condition: (object: any, value: any) => boolean, validationOptions?: ValidationOptions): PropertyDecorator {
    return ValidateIf((object: Record<string, unknown>, value: string): boolean => {
        return !condition(object, value) ? true : value !== null && value !== undefined;
    }, validationOptions);
}

i just want to ignore one validator not all

aoi-umi avatar Dec 29 '21 07:12 aoi-umi

I believe this is the best proposal for improving validator conditionality. I think #1579 needs some work to resolve this (see my comments there), but this solution is my preferred approach to making specific decorators conditional.

braaar avatar Dec 15 '23 05:12 braaar