A version of @IsOptional that would allow null but not undefined would be a great add for a lot of use cases. Additionally, a version that allowed undefined but not null would come in handy for certain operations as well - I would think this is what @IsOptional should do, but the docs state that it allows null AND undefined, which I don't think is particularly intuitive.
This seems to be related to #491
why not use a custom validator?
Right now you can accomplish this using a custom decorator.
Reposting my solution from here:
You can create "optionally null" and "optionally undefined" decorators by decorating the @ValidateIf decorator
/**
* Skips validation if the target is null
*/
function IsNullable(options?: ValidationOptions): PropertyDecorator {
return function IsNullableDecorator(prototype: Object, propertyKey: string | symbol) {
ValidateIf((obj) => (obj)[propertyKey] !== null, options)(prototype, propertyKey);
};
}
/**
* Skips validation if the target is undefined
*/
function IsUndefinable(options?: ValidationOptions): PropertyDecorator {
return function IsUndefinedDecorator(prototype: Object, propertyKey: string | symbol) {
ValidateIf((obj) => (obj)[propertyKey] !== undefined, options)(prototype, propertyKey);
};
}
Most helpful comment
Right now you can accomplish this using a custom decorator.
Reposting my solution from here:
You can create "optionally null" and "optionally undefined" decorators by decorating the @ValidateIf decorator