I dislike the functionality of IsOptional()
as it will allow null values on fields where you havent specified null in the DTO. This means you can inadvertently allow non nullable fields to be nulled.
I created a custom decorator based off another stackoverflow answer that allows a field to be undefined, but wont let it pass validation as null.
import { IsOptional, ValidateIf, ValidationOptions } from 'class-validator'
export function IsOptionalNonNullable(data?: {
nullable: boolean
validationOptions?: ValidationOptions
}) {
const { nullable = false, validationOptions = undefined } = data || {}
if (nullable) {
// IsOptional allows null
return IsOptional(validationOptions)
}
return ValidateIf((ob: any, v: any) => {
return v !== undefined
}, validationOptions)
}
// Example usage
export class SomeUpdateDTO {
@IsInt()
// Param can be undefined, but not null
@IsOptionalNonNullable()
nbOfViews?: number
}
// Example of why IsOptional is a problem
export class SomeOtherUpdateDTO {
@IsInt()
@IsOptional()
// Null is not specified, but IsOptional will allow it!
// Could end up nulling a required field in the db
nbOfViews?: number
}