e.g. for database rows, we may need nullable properties that must not be undefined:
class DbRow {
@IsNumber()
id!: number;
@IsNumber()
numNullable!: number | null;
}
So numNullable
can be a number or null
- but it must never be undefined
.
How can we express this in class-validator?
@Optional()
does not work, because that would also allow undefined
It turns out that this is possible by using conditional validation ValidateIf
:
class DbRow {
@IsNumber()
id!: number;
@IsNumber()
@ValidateIf((object, value) => value !== null)
numNullable!: number | null;
}
Here is a stackblitz example