class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

fix: @IsEnum() together with IsNotEmpty() not working if input is empty ("")

Open Thomas-1985 opened this issue 2 years ago • 3 comments

Description

Version: 0.13.2

If is use @IsEnum() to validate a string enum, validation succeeds if i validate an empty input ""

Minimal code-snippet showcasing the problem

export enum ArticleStatus {
  stop   = 'stop',
  start    = 'start',
...

export class UpdateArticleDTO {
  @IsNotEmpty()
  @IsEnum(ArticleStatus)
  status: ArticleStatus;
}

I try to validate { "status": "" }

Expected behavior

Validation should throw an error because of an empty input like for strings {"isNotEmpty":"status should not be empty"}

Actual behavior

Validation passes without an error

Thomas-1985 avatar Feb 22 '22 18:02 Thomas-1985

Any news on this? This still doesn't work in 0.3.5

Thomas-1985 avatar Jun 20 '22 20:06 Thomas-1985

Any updates?

Thomas-1985 avatar Aug 03 '22 19:08 Thomas-1985

You need to npm install -S class-transformer and then useGlobalPipes as below

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe()); // add this pipe
  await app.listen(3008);
}
bootstrap();

smilemuffie avatar Aug 31 '22 14:08 smilemuffie

I cannot reproduce. This is working as expected for me:

import { IsEnum, IsNotEmpty, validate } from 'class-validator';

export enum MyEnum {
  stop = 'stop',
  start = 'start',
}

class MyPayload {
  @IsNotEmpty()
  @IsEnum(MyEnum)
  value?: string;

  constructor(value?: string) {
    this.value = value;
  }
}

// Will pass as expected
validate(new MyPayload('stop')).then(console.log);
validate(new MyPayload('start')).then(console.log);

// Will fail as expected
validate(new MyPayload()).then(console.log);
validate(new MyPayload('')).then(console.log);
validate(new MyPayload('random value')).then(console.log);

NoNameProvided avatar Dec 16 '22 00:12 NoNameProvided

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Jan 16 '23 00:01 github-actions[bot]