Skip to content

Commit

Permalink
Handle "yes" and "no" as valid boolean type (#224)
Browse files Browse the repository at this point in the history
Co-authored-by: Aleksey Kuznetsov <[email protected]>
  • Loading branch information
kuzalekon and Aleksey Kuznetsov authored Jul 31, 2024
1 parent 292fb13 commit d8bc647
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
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

0 comments on commit d8bc647

Please sign in to comment.