From 4c4637c79678c9d5b07c59b745da4fb21fe0d7fb Mon Sep 17 00:00:00 2001 From: leemhoon00 Date: Thu, 26 Sep 2024 00:34:57 +0900 Subject: [PATCH 1/2] feat: enhance validEnumValues function to support array input for message handling Co-authored-by: koh1260 --- src/decorator/typechecker/IsEnum.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/decorator/typechecker/IsEnum.ts b/src/decorator/typechecker/IsEnum.ts index eb3d6b064b..e3e0402fb5 100644 --- a/src/decorator/typechecker/IsEnum.ts +++ b/src/decorator/typechecker/IsEnum.ts @@ -15,6 +15,9 @@ export function isEnum(value: unknown, entity: any): boolean { * Returns the possible values from an enum (both simple number indexed and string indexed enums). */ function validEnumValues(entity: any): string[] { + if (Array.isArray(entity)) { + return entity; + } return Object.entries(entity) .filter(([key, value]) => isNaN(parseInt(key))) .map(([key, value]) => value as string); From 3d2638561c8c66fd62685ed588dcf52de9250750 Mon Sep 17 00:00:00 2001 From: leemhoon00 Date: Thu, 26 Sep 2024 00:52:47 +0900 Subject: [PATCH 2/2] test: add tests for enum validation with array of strings --- ...alidation-functions-and-decorators.spec.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/functional/validation-functions-and-decorators.spec.ts b/test/functional/validation-functions-and-decorators.spec.ts index 78ceddcd6d..2a21fa7550 100644 --- a/test/functional/validation-functions-and-decorators.spec.ts +++ b/test/functional/validation-functions-and-decorators.spec.ts @@ -918,6 +918,11 @@ describe('IsEnum', () => { someProperty: MyStringEnum; } + class MyClassFour { + @IsEnum(['first', 'second']) + someProperty: 'first' | 'second'; + } + it('should not fail if validator.validate said that its valid', () => { return checkValidValues(new MyClassTwo(), validValues); }); @@ -967,6 +972,20 @@ describe('IsEnum', () => { const message = 'someProperty must be one of the following values: first, second'; return checkReturnedError(new MyClassThree(), invalidValues, validationType, message); }); + + it('should not fail if validator.validate said that its valid (array of strings)', () => { + return checkValidValues(new MyClassFour(), validStringValues); + }); + + it('should fail if validator.validate said that its invalid (array of strings)', () => { + return checkInvalidValues(new MyClassFour(), invalidValues); + }); + + it('should return error with proper message for array of strings', () => { + const validationType = 'isEnum'; + const message = 'someProperty must be one of the following values: first, second'; + return checkReturnedError(new MyClassFour(), invalidValues, validationType, message); + }); }); describe('IsDivisibleBy', () => {