Skip to content

Commit

Permalink
feat(isBoolean) Add loose option to isBoolean validator (#1676)
Browse files Browse the repository at this point in the history
* Add loose option to isBoolean validator

* Move boolean array definitions outside of function
  • Loading branch information
Bryan Brophy committed Jul 16, 2021
1 parent c87956a commit 044159d
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -93,7 +93,7 @@ Validator | Description
**isBase64(str [, options])** | check if a string is base64 encoded. options is optional and defaults to `{urlSafe: false}`<br/> 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.<br/>`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.<br/><br/>`options` is an object which defaults to `{min:0, max: undefined}`.
**isCreditCard(str)** | check if the string is a credit card.
Expand Down
13 changes: 11 additions & 2 deletions 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);
}
31 changes: 31 additions & 0 deletions test/validators.js
Expand Up @@ -8873,6 +8873,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',
Expand Down

0 comments on commit 044159d

Please sign in to comment.