class-validator

How to allow null, but forbid undefined?


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?


Solution

  • 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