Skip to content

fix(common): Support numeric string values in ParseEnumPipe - #17668

Merged
kamilmysliwiec merged 3 commits into
nestjs:masterfrom
MingLin1995:fix/parse-enum-pipe-numeric-string
Sep 14, 2026
Merged

kamilmysliwiec merged 3 commits into
nestjs:masterfrom
MingLin1995:fix/parse-enum-pipe-numeric-string

Conversation

@MingLin1995

Copy link
Copy Markdown
Contributor

PR Checklist

Please check if your PR fulfills the following requirements:

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

When using ParseEnumPipe with numeric TypeScript enums on HTTP route parameters (such as @Query() or @Param()), values are received as strings (e.g. '0'). Because ParseEnumPipe.isEnum() uses strict equality checking against numeric enum values ([0, 1].includes('0')), it throws a 400 Bad Request: "Validation failed (enum string is expected)".

Issue Number: Fixes #17638

What is the new behavior?

  1. ParseEnumPipe.isEnum() now supports numeric string values when the underlying enum values are numeric.
  2. ParseEnumPipe.transform() coerces numeric string values to numbers (Number(value)), ensuring the returned value matches the TypeScript numeric enum type instead of remaining a raw string.
  3. String enums with digit characters (e.g. enum Digit { Zero = '0' }) preserve their string type and are not coerced.
  4. Comprehensive unit tests added covering numeric strings, negative values, digit string enums, and invalid/empty strings.

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

  • All 194 unit tests in packages/common/test/pipes passed.
  • Linted with oxlint and formatted with prettier.

Comment on lines 79 to 85
if (this.isNumeric(value)) {
const enumValues = this.getEnumValues();
if (!enumValues.includes(value) && enumValues.includes(Number(value))) {
return Number(value) as T;
}
}
return value as T;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This returns Number(value) rather than the enum member that matched, and the isNumeric regex is looser than an enum lookup should be. Concretely, with enum Status { Active = 0, Inactive = 1 }:

  • '01', '00', '1.0', '0.0' are accepted and mapped to 1 / 0
  • '-0' is accepted and the pipe returns -0, not Status.Active (Object.is(-0, 0) === false)

It also walks Object.keys(enumType) a second time per call, right after isEnum already did.

I'd rather match a numeric member only by its exact string form (String(enumValue) === value) and return the member itself. Together with the helper suggested below on isEnum:

Suggested change
if (this.isNumeric(value)) {
const enumValues = this.getEnumValues();
if (!enumValues.includes(value) && enumValues.includes(Number(value))) {
return Number(value) as T;
}
}
return value as T;
return (this.toEnumValue(value) ?? value) as T;

(?? value keeps the current behavior for subclasses that override isEnum to accept something the default lookup doesn't know about.)

Comment on lines 88 to +105
protected isEnum(value: unknown): boolean {
const enumValues = Object.keys(this.enumType as object)
const enumValues = this.getEnumValues();
if (enumValues.includes(value)) {
return true;
}
if (this.isNumeric(value)) {
return enumValues.includes(Number(value));
}
return false;
}

protected isNumeric(value: unknown): boolean {
return (
['string', 'number'].includes(typeof value) &&
/^-?\d+(\.\d+)?$/.test(String(value)) &&
isFinite(value as any)
);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion to go with the comment above: a single lookup that handles both exact matches and the string form of numeric members, so we don't need isNumeric (which is a near copy of ParseIntPipe.isNumeric with (\.\d+)? added) and the regex / isFinite / Number() dance:

Suggested change
protected isEnum(value: unknown): boolean {
const enumValues = Object.keys(this.enumType as object)
const enumValues = this.getEnumValues();
if (enumValues.includes(value)) {
return true;
}
if (this.isNumeric(value)) {
return enumValues.includes(Number(value));
}
return false;
}
protected isNumeric(value: unknown): boolean {
return (
['string', 'number'].includes(typeof value) &&
/^-?\d+(\.\d+)?$/.test(String(value)) &&
isFinite(value as any)
);
}
protected isEnum(value: unknown): boolean {
return this.toEnumValue(value) !== undefined;
}
/**
* Returns the enum member that `value` refers to, or `undefined` if there is none.
* Numeric members also match their string representation (e.g. `'1'` for `1`),
* since HTTP route and query params always arrive as strings.
*/
protected toEnumValue(value: unknown): string | number | undefined {
return this.getEnumValues().find(
enumValue =>
enumValue === value ||
(typeof enumValue === 'number' &&
typeof value === 'string' &&
String(enumValue) === value),
);
}

I ran this variant locally against the spec in this PR plus a set of edge cases: all of the existing tests still pass, '0' / '1' / '-5' / '100' / '0.5' (for a float-valued member) resolve to the member, string enums with digit values are untouched, and '01', '1.0', '-0', '+1', ' 1', '1e0' are rejected.

Note that isNumeric is protected, so keeping it means committing to it as an extension point (see #9496). If you'd rather keep the regex approach, please at least make it private and drop the (\.\d+)? part unless float-valued enums get a test.

);
}

protected getEnumValues(): any[] {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this can be typed as (string | number)[], which is what enum members can be at runtime. Exposing it as a protected extension point seems fine to me.

Comment on lines +95 to +102
it('should return numeric enum value when the numeric value is passed as a string', async () => {
expect(
await numericTarget.transform('0' as any, {} as ArgumentMetadata),
).toBe(Status.Active);
expect(
await numericTarget.transform('1' as any, {} as ArgumentMetadata),
).toBe(Status.Inactive);
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also pin down the edge cases that the coercion decides on, whatever we settle on (my preference is that these are all rejected):

  • '01', '1.0' and '-0' for the Status enum
  • a mixed enum (enum Mixed { A = 'a', One = 1 }) with 'a', '1' and 1

And, since the regex intentionally allows decimals, a float-valued enum (e.g. enum Ratio { Half = 0.5 }) with '0.5'. Otherwise that branch of the regex is untested.

Comment on lines +104 to +108
it('should throw when an invalid numeric string is passed', async () => {
await expect(
numericTarget.transform('2' as any, {} as ArgumentMetadata),
).rejects.toThrow(HttpException);
});

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HttpException is the base class of every built-in HTTP exception, so this would also pass if the pipe started throwing, say, a 500. Assert the concrete one (BadRequestException, and ideally the message) here and in the test below.

@micalevisk

Copy link
Copy Markdown
Member

Thanks for the PR! A few things before the inline notes.

Context / prior art

Review

Requesting changes for the points below. The behavior for the happy path ('0' -> 0, '-5' -> -5, string enums with digit values untouched) is right and well covered; the concerns are about how loose the coercion is and the shape of the implementation.

  1. The coercion is looser than an enum check should be. With the current isNumeric + Number(value) approach, '00', '01', '1.0' and '0.0' are all accepted and mapped to enum members, and '-0' is accepted but returns -0 instead of the member 0. For an enum I'd expect only the exact string form of a numeric member to match. See the inline suggestion: comparing against String(enumValue) and returning the matched member is simpler (no regex, no isFinite, no Number()), stricter, and avoids the second getEnumValues() pass in transform.
  2. Tests should pin whichever leniency we decide on ('01', '1.0', '-0'), cover a mixed string/number enum, and, if decimals are intentionally supported (the regex has (\.\d+)?), cover a float-valued enum. Also prefer asserting BadRequestException over the base HttpException.
  3. isNumeric and getEnumValues are new protected members, i.e. part of the pipe's extensibility surface (see feat(common): improve extensibility on few built-in pipes #9496). getEnumValues is a reasonable extension point; isNumeric is a near copy of ParseIntPipe.isNumeric and shouldn't be needed with the approach above.
  4. If we land this as a feature, the PR description should say so (PR type + feat(common) commit) and it'd be worth a one-liner in the docs (pipes chapter on docs.nestjs.com) mentioning that ParseEnumPipe accepts the string form of numeric enum members.

Possible follow-ups (not for this PR)

  • Extract a shared numeric-string check for ParseIntPipe / ParseFloatPipe / this pipe instead of three slightly different isNumeric implementations.
  • ParseEnumPipe<T> types T as the enum object, so every as T on a member value (pre-existing and here) is misleading. Worth a typing cleanup at some point.

CI: the only red job is samples, which timed out at 60 min and is unrelated to this change (build, lint, unit and integration jobs are green).

@MingLin1995

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and suggestions @micalevisk !
I've updated the implementation to use toEnumValue with exact string matching (String(enumValue) === value), removed isNumeric, typed getEnumValues as (string | number)[], and added tests for edge cases ('01', '-0', '1.0', etc.), mixed enums, and float enums, asserting BadRequestException.

transform() calls isEnum() and toEnumValue(), each of which rebuilt the
enum value list via Object.keys().filter().map() on every request. The
enum object is fixed at construction, so compute the list lazily once
and reuse it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kamilmysliwiec
kamilmysliwiec merged commit 02ee6d4 into nestjs:master Sep 14, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ParseEnumPipe fails validation for numeric enum values when passed as strings (e.g., from @Query or @Param)

3 participants