class-validator
class-validator copied to clipboard
feat: add `skipIf` predicate option to decorator options
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;
}
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);
}
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
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.