Search code examples
typescriptnestjsclass-validator

Prevent Null value on NestJs dto properties


I want to prevent null value on nestjs dto optional properties.

@ApiProperty({
  type: String,
  format: 'string',
})
@IsOptional()
@IsString()
readonly name?: string;

A possible workaround is this:

@ApiProperty({
  type: String,
  format: 'string',
  required: false, // This will make it optional for the docs
})
@ValidateIf((o) => o.name !== undefined) 
@IsString()
readonly name?: string;

I'm expecting something like: @IsNotNull


Solution

  • As discussed in the comments, you have a fair and valid point that you want to have a clean self-explanatory decorator. But unfortunately, the behavior of class-validator's @IsOptional makes it impossible to be used with other decorators to not allow null like @NotEquals(null)...

    @IsOptional() Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property.

    And I didn't find any initiative YET from the library's maintainers to add a cleaner approach to achieve it, check these open issues:

    Now it's up to you, you can implement your own decorator and import it to your DTO class, or use a library that does that for you like class-validator-extended, it seems that they offer an @Optional decorator (note that they suggest that you import from class-validator-extended/dist/minimal if you don't have dayjs).

    If you don't want to have the full npm package installed just to use that one decorator, I believe that you can just get inspired by this portion from class-validator-extended/optional.decorator.ts#L21