diff --git a/CHANGELOG.md b/CHANGELOG.md index 41627af..0b13978 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ ## Changelog -### [v5.19.3](https://github.com/panates/valgen/compare/v5.19.2...v5.19.3) - +### [v5.19.4](https://github.com/panates/valgen/compare/v5.19.3...v5.19.4) - + +#### 🚀 New Features + +- feat: Handle TypeScript enums in isEnum validator @Eray Hanoğlu + +### [v5.19.3](https://github.com/panates/valgen/compare/v5.19.2...v5.19.3) - 19 January 2026 #### 🪲 Fixes diff --git a/package-lock.json b/package-lock.json index 15a3ec9..2c7da01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "valgen", - "version": "5.19.3", + "version": "5.19.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "valgen", - "version": "5.19.3", + "version": "5.19.4", "license": "MIT", "dependencies": { "@browsery/validator": "^13.15.15", diff --git a/package.json b/package.json index 4d246e1..7f15c38 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "valgen", "description": "Fast runtime type validator, converter and io (encoding/decoding) library", - "version": "5.19.3", + "version": "5.19.4", "author": "Panates", "license": "MIT", "private": true, diff --git a/src/rules/type-rules/is-enum.ts b/src/rules/type-rules/is-enum.ts index 8e7b7da..524ba29 100644 --- a/src/rules/type-rules/is-enum.ts +++ b/src/rules/type-rules/is-enum.ts @@ -9,16 +9,24 @@ import { * Validates if given value is one of enum values. * @validator isEnum */ -export function isEnum( - values: I1 | I1[], +export function isEnum( + values: any, options?: ValidationOptions & { caseInSensitive?: boolean; enumName?: string; }, -): Validator { +): Validator { const caseInSensitive = !!options?.caseInSensitive; const enumName = options?.enumName; // Prepare an object for fast lookup + if (values && typeof values === 'object' && !Array.isArray(values)) { + const keys = Object.keys(values).filter(k => !/^\d+$/.test(k)); + values = keys.reduce((a, k) => { + if (values[k] != null) a.push(values[k]); + return a; + // v => !(typeof v === 'number' && !keys.includes(String(v))), + }, [] as any[]); + } const valObj = (Array.isArray(values) ? values : [values]).reduce( (a, v) => { if (typeof v === 'string' && caseInSensitive) a[v.toUpperCase()] = true; diff --git a/test/type-rules/is-enum.spec.ts b/test/type-rules/is-enum.spec.ts index b5a67e1..d8c843d 100644 --- a/test/type-rules/is-enum.spec.ts +++ b/test/type-rules/is-enum.spec.ts @@ -12,4 +12,17 @@ describe('isEnum', () => { ); expect(() => vg.isEnum(['a', 'b'])(null as any)).toThrow('must be one of'); }); + + it('should validate value using TypeScript enums', () => { + enum Enum1 { + a = 0, + b = 1, + } + enum Enum2 { + a = 'a', + b = 'b', + } + expect(vg.isEnum(Enum1)(0)).toStrictEqual(0); + expect(vg.isEnum(Enum2)('a')).toStrictEqual('a'); + }); });