diff --git a/README.md b/README.md index 67496d8b5..560046644 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Validator | Description **isBase64(str [, options])** | check if a string is base64 encoded. options is optional and defaults to `{urlSafe: false}`
when `urlSafe` is true it tests the given base64 encoded string is [url safe](https://base64.guru/standards/base64url) **isBefore(str [, date])** | check if the string is a date that's before the specified date. **isBIC(str)** | check if a string is a BIC (Bank Identification Code) or SWIFT code. -**isBoolean(str)** | check if a string is a boolean. +**isBoolean(str [, options])** | check if a string is a boolean.
`options` is an object which defaults to `{ loose: false }`. If loose is is set to false, the validator will strictly match ['true', 'false', '0', '1']. If loose is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (eg: ['true', 'True', 'TRUE']). **isBtcAddress(str)** | check if the string is a valid BTC address. **isByteLength(str [, options])** | check if the string's length (in UTF-8 bytes) falls in a range.

`options` is an object which defaults to `{min:0, max: undefined}`. **isCreditCard(str)** | check if the string is a credit card. diff --git a/src/lib/isBoolean.js b/src/lib/isBoolean.js index e7cb27dfa..9fddc2b48 100644 --- a/src/lib/isBoolean.js +++ b/src/lib/isBoolean.js @@ -1,6 +1,15 @@ import assertString from './util/assertString'; -export default function isBoolean(str) { +const defaultOptions = { loose: false }; +const strictBooleans = ['true', 'false', '1', '0']; +const looseBooleans = [...strictBooleans, 'yes', 'no']; + +export default function isBoolean(str, options = defaultOptions) { assertString(str); - return (['true', 'false', '1', '0'].indexOf(str) >= 0); + + if (options.loose) { + return looseBooleans.includes(str.toLowerCase()); + } + + return strictBooleans.includes(str); } diff --git a/test/validators.js b/test/validators.js index c7119487b..6d26ee2e6 100644 --- a/test/validators.js +++ b/test/validators.js @@ -8870,6 +8870,37 @@ describe('Validators', () => { }); }); + it('should validate booleans with option loose set to true', () => { + test({ + validator: 'isBoolean', + args: [ + { loose: true }, + ], + valid: [ + 'true', + 'True', + 'TRUE', + 'false', + 'False', + 'FALSE', + '0', + '1', + 'yes', + 'Yes', + 'YES', + 'no', + 'No', + 'NO', + ], + invalid: [ + '1.0', + '0.0', + 'true ', + ' false', + ], + }); + }); + const validISO8601 = [ '2009-12T12:34', '2009',