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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down