Damon
Damon

Reputation: 4484

How can I allow an empty string value for optional enum with NestJs?

I am successfully validating my dto for valid enum types:

// time-unit.enum.ts

export enum TimeUnit {
  SECONDS = 'SECONDS',
  MINUTES = 'MINUTES',
  HOURS = 'HOURS',
  DAYS = 'DAYS',
}
// create-thing.dto.ts

@ApiPropertyOptional({
    description: 'The lead time unit.',
    example: 'DAYS',
  })
  @IsOptional()
  @IsEnum(TimeUnit)
  unit?: TimeUnit;

On the front-end, I am providing a <select> that is populated with an empty string for default value, then the corresponding enum values.

If I choose a value, everything works great! This is an optional field (a nullable column). So If I attempt to save without choosing something, I'll get a 400 error:

leadTime.unit must be a valid enum value

How can I allow an empty string as a valid enum option?

Upvotes: 5

Views: 4284

Answers (1)

Roman Matkivskyy
Roman Matkivskyy

Reputation: 86

The best way is to transform the the value if its equal to empty string // create-thing.dto.ts

@ApiPropertyOptional({
    description: 'The lead time unit.',
    example: 'DAYS',
  })
  @Transform((params) => (params.value === '' ? null : params.value))
  @IsOptional()
  @IsEnum(TimeUnit)
  unit?: TimeUnit;

Upvotes: 7

Related Questions