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

Handle "yes" and "no" as valid boolean type #224

Merged
merged 4 commits into from
Jul 31, 2024
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ URL, email address). To these ends, the following validation functions are avail
- `str()` - Passes string values through, will ensure a value is present unless a
`default` value is given. Note that an empty string is considered a valid value -
if this is undesirable you can easily create your own validator (see below)
- `bool()` - Parses env var strings `"1", "0", "true", "false", "t", "f"` into booleans
- `bool()` - Parses env var strings `"1", "0", "true", "false", "t", "f", "yes", "no", "on", "off"` into booleans
- `num()` - Parses an env var (eg. `"42", "0.23", "1e5"`) into a Number
- `email()` - Ensures an env var is an email address
- `host()` - Ensures an env var is either a domain name or an ip address (v4 or v6)
Expand Down
4 changes: 4 additions & 0 deletions src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,15 @@ export const bool = makeExactValidator<boolean>((input: string | boolean) => {
case true:
case 'true':
case 't':
case 'yes':
case 'on':
case '1':
return true
case false:
case 'false':
case 'f':
case 'no':
case 'off':
case '0':
return false
default:
Expand Down
10 changes: 10 additions & 0 deletions tests/validators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ test('bool() works with various formats', () => {
const f = cleanEnv({ FOO: 'f' }, { FOO: bool() })
expect(f).toEqual({ FOO: false })

const yes = cleanEnv({ FOO: 'yes'}, { FOO: bool() })
expect(yes).toEqual({ FOO: true })
const no = cleanEnv({ FOO: 'no' }, { FOO: bool() })
expect(no).toEqual({ FOO: false })

const on = cleanEnv({ FOO: 'on'}, { FOO: bool() })
expect(on).toEqual({ FOO: true })
const off = cleanEnv({ FOO: 'off' }, { FOO: bool() })
expect(off).toEqual({ FOO: false })

const defaultF = cleanEnv({}, { FOO: bool({ default: false }) })
expect(defaultF).toEqual({ FOO: false })
})
Expand Down
Loading