Skip to content
Merged
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
8 changes: 6 additions & 2 deletions src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,12 @@ export const bool = makeExactValidator<boolean>((input: string | boolean) => {
})

export const num = makeValidator<number>((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
})

Expand Down
10 changes: 10 additions & 0 deletions tests/validators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()', () => {
Expand Down
Loading