Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enhance validEnumValues function to support array input for message #2537

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/decorator/typechecker/IsEnum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
19 changes: 19 additions & 0 deletions test/functional/validation-functions-and-decorators.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down Expand Up @@ -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', () => {
Expand Down