From a3597f566e1a768071e3ac6d1c22f878f55e218d Mon Sep 17 00:00:00 2001 From: Aaron Franks Date: Mon, 9 Nov 2026 20:53:48 -0700 Subject: [PATCH] num validator: throw when number value has invalid chars --- src/validators.ts | 8 ++++++-- tests/validators.test.ts | 10 ++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/validators.ts b/src/validators.ts index 03981eb..882c3c7 100644 --- a/src/validators.ts +++ b/src/validators.ts @@ -52,8 +52,12 @@ export const bool = makeExactValidator((input: string | boolean) => { }) export const num = makeValidator((input: string) => { - const coerced = parseFloat(input) - if (Number.isNaN(coerced)) throw new EnvError(`Invalid number input: "${input}"`) + // Number() rejects trailing garbage ("30s") but accepts hex/binary/octal ("0x10"); + // parseFloat() rejects those prefixes and empty strings. Require both to agree. + const coerced = Number(input) + if (Number.isNaN(coerced) || coerced !== parseFloat(input)) { + throw new EnvError(`Invalid number input: "${input}"`) + } return coerced }) diff --git a/tests/validators.test.ts b/tests/validators.test.ts index 1ea1d14..aa78f65 100644 --- a/tests/validators.test.ts +++ b/tests/validators.test.ts @@ -70,6 +70,16 @@ test('num()', () => { expect(() => cleanEnv({ FOO: 'asdf' }, { FOO: num() }, makeSilent)).toThrow() expect(() => cleanEnv({ FOO: '' }, { FOO: num() }, makeSilent)).toThrow() + expect(() => cleanEnv({ FOO: ' ' }, { FOO: num() }, makeSilent)).toThrow() + + // Malformed values with trailing characters should be rejected, not truncated (#261) + // Note that the number variable explicitly DOES NOT support hex/binary/octal formats + for (const bad of ['10_000', '30s', '1.2.3', '0x10', '0b11', '0o7']) { + expect(() => cleanEnv({ FOO: bad }, { FOO: num() }, makeSilent)).toThrow() + } + + const withNegative = cleanEnv({ FOO: '-1.5' }, { FOO: num() }) + expect(withNegative).toEqual({ FOO: -1.5 }) }) test('email()', () => {